/**
 * Created by wry on 2014/12/11.
 */

var Question = mongoose.model('question');
/*  宝宝树66小区二次改造    add   guoct  20170722   start   */
var Goods = mongoose.model('goods');
/*  宝宝树66小区二次改造    add   guoct  20170722   end   */
var QuestionReplyStatistics = mongoose.model('question_replystatistics');
var Dic = mongoose.model('masterData_Dictionaries');
var Community = mongoose.model('community');
var toolUtil = require('../common/utils/toolUtil');
var messageUtil = require('../common/utils/messageUtil');
var Users = mongoose.model('user');
var async = require('async');
var UserFollowups = mongoose.model('user_followups');
var SystemMessage = mongoose.model('system_messages');
var questionService = require('../services/questionService');
var moment = require('moment');
var QuestionReplyPraise = mongoose.model('question_replypraises');
var QuestionReport = mongoose.model('question_reports');
var QuestionAndReplyCount = mongoose.model('question_replycounts');
var QuestionReplyThank = mongoose.model('question_replythanks');
var freshNews = mongoose.model('system_freshNews');
var pushRecords = mongoose.model('system_pushRecords');
var ugcIndex = mongoose.model('system_ugcIndex');
var topic = mongoose.model('topic');
var neighbourActivity = mongoose.model('activity_neighbour');
var ugcReply = mongoose.model('system_ugcReply');
var AdoptedCount = mongoose.model('question_adoptedcounts');
var replyAt = mongoose.model('question_replyAt');
var recentContact = mongoose.model('user_recentContactPerson');
var replyAtService = mongoose.model('question_replyAtService');
var questionPraise = mongoose.model('question_praise');
var shareService = require('../services/mobile/sharesService');
var Banner = mongoose.model('community_banner');
var BannerBind = mongoose.model('community_banner_bind');
var replyIndex = mongoose.model('reply_index');
var taskService = require('./taskService');
var redisKey = require('../config/redisKey');
var geolib = require('geolib');
var userCommunity = mongoose.model('user_community');
/*  宝宝树66小区二次改造    mod   chnef  20170821   start   */
var GoodsReport = mongoose.model('goods_reports');
/*  宝宝树66小区二次改造    mod   chnef  20170821   start   */
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170912   start   */
var userService = require('./userService');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170912   end   */
/**
 * ==================================提问==================================
 */

/**
 * 提问新接口
 * @param token
 * @param input
 * @param callback
 */
exports.postQuestionNewService = function (token, input, callback) {

    var pushFlag = input.category;

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var question;
            var tags;
            var tag;
            var desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

            var temp = new Question();
            temp.category = input.category;
            temp.desc = desc;
            temp.images = input.images;
            temp.status = '未解决';
            temp.createdBy = user._id;
            temp.community = user.community._id;
            temp.aroundCommunity = input.aroundCommunity;

            //打标签
            //  宝宝树66小区二次改造   recommond失效 mod  luolh  20170724   start
            // restClient.get('http://' + RecommendHost + ':8002?data=' + input.desc, function (data, response) {
            //     if (response.statusCode == 200 && data != null && data != 'unknown' && data != '') {
            //         try {
            //             var sensitive = JSON.parse(data).sensitive;
            //             tags = JSON.parse(data).tag;
            //
            //             if (sensitive != null) {
            //                 temp.desc = sensitive;
            //                 input.desc = sensitive;
            //             }
            //
            //             Dic.find({'value': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
            //                 if (res != null) {
            //                     temp.tag = res;
            //                     tag = res;
            //                 }
            //                 temp.save(function (err, result) {
            //
            //                     var data = {
            //                         question: result,
            //                         tag: tag,
            //                         tags: tags,
            //                         user: user,
            //                         input: input,
            //                         pushFlag: pushFlag,
            //                         communityName: user.community.communityName
            //                     };
            //
            //                     callback(null, data);
            //                 });
            //             });
            //         } catch (e) {
            //             logger.error("postNewQuestion--tag--" + e);
            //             temp.save(function (err, result) {
            //                 var data = {
            //                     question: result,
            //                     tag: tag,
            //                     tags: tags,
            //                     user: user,
            //                     input: input,
            //                     pushFlag: pushFlag,
            //                     communityName: user.community.communityName
            //                 };
            //                 callback(null, data);
            //             })
            //         }
            //     } else {
            //         temp.save(function (err, result) {
            //             var data = {
            //                 question: result,
            //                 tag: tag,
            //                 tags: tags,
            //                 user: user,
            //                 input: input,
            //                 pushFlag: pushFlag,
            //                 communityName: user.community.communityName
            //             };
            //             callback(null, data);
            //         })
            //     }
            // }).on('error', function (err) {
            //     logger.error('get question tag around went wrong on the request' + err.message);
            //
            //     temp.save(function (err, result) {
            //         var data = {
            //             question: result,
            //             tag: tag,
            //             tags: tags,
            //             user: user,
            //             input: input,
            //             pushFlag: pushFlag,
            //             communityName: user.community.communityName
            //         };
            //         callback(null, data);
            //     })
            // });
                temp.save(function (err, result) {
                    var data = {
                        question: result,
                        tag: tag,
                        tags: tags,
                        user: user,
                        input: input,
                        pushFlag: pushFlag,
                        communityName: user.community.communityName
                    };
                    callback(null, data);
                });
            //  宝宝树66小区二次改造   recommond失效 mod  luolh  20170724   end
        }
    });
};

exports.pushQuestionService = function (user, tag, tags, question, input, pushFlag) {
    async.series([
        //推送给已关注问题发起者的用户
        function (callbackInner) {
            UserFollowups.find({'followUser': question.createdBy}, 'user').populate('user', '_id community').exec(function (err, results) {
                if (results != null && results.length > 0) {

                    var users = [];
                    results.forEach(function (result) {

                        if (result.user != null && user.community._id == result.user.community) {
                            var temp = new SystemMessage();
                            temp.toUser = result.user._id;
                            temp.content.questionDesc = '';
                            temp.content.replyDesc = input.desc;
                            temp.content.title = user.nickName;
                            temp.content.contentId = question._id;
                            temp.content.contentType = 'myFollowupUser';
                            temp.content.questionCreatedBy = question.createdBy;
                            temp.category = 'question';
                            temp.fromUser = user._id;
                            temp.save();

                            users.push(result.user._id);
                        }
                    });

                    //个推
                    var content = {
                        type: 1,
                        flag: 1,
                        openType: 1,
                        contentId: question._id,
                        createdBy: question.createdBy,
                        desc: user.nickName + ':' + question.desc
                    };
                    var pushData = {
                        uList: users,
                        content: content,
                        type: 'user'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);
                }
                callbackInner(null, 1);
            });
        },
        //统计
        function (callbackInner) {
            if (tags == null) {
                tags = ['全部']
            } else {
                tags.push('全部')
            }
            Dic.find({'value': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
                res.forEach(function (tag) {
                    QuestionAndReplyCount.findOne({
                        'community': question.community,
                        'tag': tag
                    }, function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.questionCount = 1;
                            temp.community = question.community;
                            temp.tag = tag;
                            temp.save();
                        } else {
                            qc.questionCount += 1;
                            qc.save();
                        }
                    })
                })
            });
            //redis统计
            if (question.category != null)
                redisClient.hincrby('q:count:' + question.community, question.category + 'QuestionCount', 1);
            callbackInner(null, 1);
        },
        function (callbackInner) {   //建立索引
            var temp = new ugcIndex();
            temp.ugcId = question._id;
            temp.category = input.category;
            temp.community = question.community;
            temp.createdBy = question.createdBy;
            temp.aroundCommunity = question.aroundCommunity;
            if (tag != null)
                temp.tag = tag;
            temp.save(callbackInner);
        },
        function (callbackInner) {
            if (pushFlag == 'activity') {
                Question.findOne({community: user.community._id, fromFlag: 'service'}, function (err, result) {
                    var content = {
                        type: 1,
                        flag: 2,
                        openType: 1,
                        contentId: result._id,
                        createdBy: result.createdBy,
                        desc: result.desc
                    };
                    var pushData = {
                        uList: [user._id],
                        content: content,
                        tag: '话题',
                        type: 'operate'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);
                });
            }
            callbackInner();
        }
    ])
};

/**
 * 增加提问
 */
exports.postQuestionService = function (token, input, callback) {
    var nickName;

    async.waterfall([
            function (callbackInner) {
                Users.findOne({'_id': toolUtil.getUserObjIdByToken(token)}, function (err, result) {
                    Dic.findOne({'value': '全部', 'category': '02'}, '_id', function (err, res) {
                        QuestionAndReplyCount.findOne({
                            'community': result.community,
                            'tag': res
                        }, '', function (err, qc) {
                            if (qc == null) {
                                var temp = new QuestionAndReplyCount();
                                temp.questionCount = 1;
                                temp.community = result.community;
                                temp.tag = res;
                                temp.save();
                            } else {
                                qc.questionCount += 1;
                                qc.save();
                            }
                        })
                    });
                    nickName = result.nickName;
                    callbackInner(null, result);
                })
            },
            function (result, callbackInner) {
                if (result == undefined) {
                    var err = {
                        "message": 'User not found'
                    };
                    callback(err, null);
                } else {
                    //  宝宝树66小区二次改造   recommond失效 mod  luolh  20170724   start
                    // restClient.get('http://' + RecommendHost + ':8002?data=' + input.desc, function (data, response) {
                    //     if (response.statusCode == 200) {
                    //         var temp = new Question();
                    //         temp.category = input.category;
                    //         temp.desc = input.desc;
                    //         temp.status = '未解决';
                    //         temp.createdBy = result._id;
                    //         temp.community = result.community;
                    //
                    //
                    //         if (data == null || data == 'unknown') {
                    //             temp.save(function (err, question) {
                    //                 callbackInner(null, question);
                    //             })
                    //         } else {
                    //             var sensitive = JSON.parse(data).sensitive;
                    //             if (sensitive != null) {
                    //                 temp.desc = sensitive;
                    //                 temp.save(function (err, question) {
                    //                     callbackInner(null, question);
                    //                 })
                    //             } else {
                    //                 var tags = new Array();
                    //
                    //                 tags = JSON.parse(data).tag;
                    //                 Dic.find({
                    //                     'value': {'$in': tags},
                    //                     'category': '02'
                    //                 }, '_id', function (err, res) {
                    //                     if (res == null) {
                    //                         temp.save(function (err, question) {
                    //                             callbackInner(null, question);
                    //                         });
                    //                     } else {
                    //                         temp.tag = res;
                    //                         temp.save(function (err, question) {
                    //                             callbackInner(null, question);
                    //                         });
                    //                         res.forEach(function (tag) {
                    //                             QuestionAndReplyCount.findOne({
                    //                                 'community': result.community,
                    //                                 'tag': tag
                    //                             }, '', function (err, qc) {
                    //                                 if (qc == null) {
                    //                                     var temp = new QuestionAndReplyCount();
                    //                                     temp.questionCount = 1;
                    //                                     temp.community = result.community;
                    //                                     temp.tag = tag;
                    //                                     temp.save();
                    //                                 } else {
                    //                                     qc.questionCount += 1;
                    //                                     qc.save();
                    //                                 }
                    //                             })
                    //                         })
                    //                     }
                    //                 })
                    //             }
                    //         }
                    //     } else {
                    //         var temp = new Question();
                    //         temp.category = input.category;
                    //         temp.desc = input.desc;
                    //         temp.status = '未解决';
                    //         temp.createdBy = result._id;
                    //         temp.community = result.community;
                    //
                    //         temp.save(function (err, question) {
                    //             callbackInner(null, question);
                    //         })
                    //     }
                    // }).on('error', function (err) {
                    //     logger.error('get question tag around went wrong on the request' + err.message);
                    //
                    //     var temp = new Question();
                    //     temp.category = input.category;
                    //     temp.desc = input.desc;
                    //     temp.status = '未解决';
                    //     temp.createdBy = result._id;
                    //     temp.community = result.community;
                    //
                    //     temp.save(function (err, question) {
                    //         callbackInner(null, question);
                    //     })
                    // });
                    var temp = new Question();
                    temp.category = input.category;
                    temp.desc = input.desc;
                    temp.status = '未解决';
                    temp.createdBy = result._id;
                    temp.community = result.community;

                    temp.save(function (err, question) {
                        callbackInner(null, question);
                    });
                    //  宝宝树66小区二次改造   recommond失效 mod  luolh  20170724   end
                }
            },
            function (result, callbackInner) {
                //推送给已关注问题发起者的用户
                UserFollowups.find({'followUser': result.createdBy}, 'user', function (err, results) {
                    if (results != null && results.length > 0) {

                        var users = [];
                        results.forEach(function (user) {

                            var temp = new SystemMessage();
                            temp.toUser = user.user;
                            temp.content.questionDesc = '';
                            temp.content.replyDesc = input.desc;
                            temp.content.title = nickName;
                            temp.content.contentId = result._id;
                            temp.content.contentType = 'myFollowupUser';
                            temp.content.questionCreatedBy = result.createdBy;
                            temp.category = 'question';
                            temp.fromUser = toolUtil.getUserObjIdByToken(token);
                            temp.save();

                            users.push(user.user);
                        });


                        //个推
                        var content = {
                            type: 1,
                            flag: 1,
                            openType: 1,
                            contentId: result._id,
                            createdBy: result.createdBy,
                            desc: nickName + ':' + result.desc
                        };
                        var pushData = {
                            uList: users,
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                });

                //统计
                //var tag = result.tag;
                //if (tag != null) {
                //    Users.find({
                //        'community': result.community,
                //        'domainOfExpertise': result.tag
                //    }, '_id nickName domainOfExpertise images').populate('domainOfExpertise', '_id value')
                //        .exec(function (err, users) {
                //            if (users != null && users.length != 0) {
                //                async.each(users, function (user, callback) {
                //                    Question.count({'replies.repliedBy': user._id}, function (err, count) {
                //                        user._doc['totalReplied'] = count;
                //                        user._doc['totalFans'] = 70;
                //                        callback();
                //                    })
                //                }, function (err) {
                //                    if (err) {
                //                        var temp = {
                //                            "_id": result._id
                //                        };
                //                        callbackInner(null, temp);
                //                    } else {
                //                        var temp = {
                //                            "_id": result._id,
                //                            "expertList": users
                //                        };
                //                        callbackInner(null, temp);
                //                    }
                //                })
                //
                //            } else {
                //                var temp = {
                //                    "_id": result._id
                //                };
                //                callbackInner(null, temp);
                //            }
                //        })
                //} else {
                //var temp = {
                //    "_id": result._id
                //};
                //callbackInner(null, temp);
                //}

                if (input.category != null)
                    redisClient.hincrby('q:count:' + result.community, input.category + 'QuestionCount', 1);
                var temp = {
                    "_id": result._id
                };
                callbackInner(null, temp);
            }
        ],
        callback
    )
    ;
}
;

/**
 * 上传问题图片
 */
exports.setImagesToQuestion = function (questionId, images, callback) {
    Question.update({_id: questionId}, {$pushAll: {'images': images}}, callback);
};

/**
 * 修改提问
 */
exports.updateQuestionService = function (questionId, input, callback) {
    Question.update({_id: questionId}, input).exec(callback);
};

/**
 * 删除提问
 */
exports.deleteQuestionService = function (questionId, callback) {

    Question.findOne({'_id': questionId}, function (err, result) {

        if (!result.isValid) {
            callback({message: '帖子已被删除'})
        } else {
            if (result.replies != null) {
                result.replies.forEach(function (reply) {
                    toolUtil.changeUserStatistics(reply.repliedBy, reply.community, 'questionReply', -1);
                })
            }
            Question.update({_id: questionId}, {isValid: false}).exec(function (err, result) {
                callback(err, result);
            });


            async.parallel([
                function (callbackInner) {
                    UserFollowups.remove({'question': questionId}, callbackInner)
                },
                function (callbackInner) {
                    SystemMessage.remove({'content.contentId': questionId}, callbackInner);
                },
                function (callbackInner) {
                    replyIndex.remove({contentId: questionId}, callbackInner);
                }
            ], function () {
                logger.debug('----deleteQuestionService success')
            });
        }
    });
};

/**
 * 删除提问图片
 */
exports.deleteQuestionImagesService = function (questionId, images, callback) {
    Question.update({
        _id: questionId,
        'images.imageURL': {$in: images.images}
    }, {'$set': {'images.$.isValid': false}}).exec(callback);
};

/**
 * 举报问题
 */
exports.reportQuestionService = function (token, questionId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReport.findOne({
                'question': questionId,
                'reportUser': user._id
            }, '', function (err, result) {
                if (err) {
                    callback(err, result);
                } else {
                    if (result == null) {
                       /*  宝宝树66小区二次改造    mod   guoct  20170722   start   */
                       /* Question.findOne({_id: questionId}, function (err, question) {
                            if (question == null) {
                                callback({message: '无此问题'})
                            } else {
                                var temp = new QuestionReport();
                                temp.question = questionId;
                                temp.reportUser = user._id;
                                temp.questionCommunity = question.community;
                                temp.questionCreateBy = question.createdBy;
                                temp.save(callback);
                            }
                        })*/

                        Question.findOne({_id: questionId}, function (err, question) {
                            var flag=0;
                            if (question == null) {
                                flag=1;
                                Goods.findOne({_id: questionId}, function (err, question) {
                                    if (question == null) {
                                        callback({message: '无此问题'})
                                    } else {
                                        var temp = new QuestionReport();
                                        temp.flag=flag;
                                        temp.question = questionId;
                                        temp.reportUser = user._id;
                                        temp.questionCommunity = question.community;
                                        temp.questionCreateBy = question.createdBy;
                                        temp.save(callback);
                                    }
                                })
                            } else {
                                var temp = new QuestionReport();
                                temp.flag=flag;
                                /*  宝宝树66小区二次改造    mod   guoct  20170722   end   */
                                temp.question = questionId;
                                temp.reportUser = user._id;
                                temp.questionCommunity = question.community;
                                temp.questionCreateBy = question.createdBy;
                                temp.save(callback);
                            }
                        })

                    } else {
                        var msg = {
                            "message": "已经举报过了"
                        };
                        callback(msg, null);
                    }
                }
            })
        }
    });
};

/*  宝宝树66小区二次改造    mod   chenf  20170821   start   追加举报区分闲置和帖子*/
/**
 * 举报问题新接口
 */
exports.reportQuestionNewService = function (token, questionId,statusFlg, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            // 帖子举报
            if(statusFlg == 1){
                QuestionReport.findOne({
                    'question': questionId,
                    'reportUser': user._id
                }, '', function (err, result) {
                    if (err) {
                        callback(err, result);
                    } else {
                        if (result == null) {
                            Question.findOne({_id: questionId}, function (err, question) {
                                if (question == null) {
                                    callback({message: '无此问题'})
                                } else {
                                    var temp = new QuestionReport();
                                    temp.question = questionId;
                                    temp.reportUser = user._id;
                                    temp.questionCommunity = question.community;
                                    temp.questionCreateBy = question.createdBy;
                                    temp.save(callback);
                                }
                            })
                        } else {
                            var msg = {
                                "message": "已经举报过了"
                            };
                            callback(msg, null);
                        }
                    }
                })
            }else{
                GoodsReport.findOne({
                    'goods': questionId,
                    'reportUser': user._id
                }, '', function (err, result) {
                    if (err) {
                        callback(err, result);
                    } else {
                        if (result == null) {
                            Goods.findOne({_id: questionId}, function (err, question) {
                                if (question == null) {
                                    callback({message: '无此问题'})
                                } else {
                                    var temp = new GoodsReport();
                                    temp.goods = questionId;
                                    temp.reportUser = user._id;
                                    temp.goodsCommunity = question.community;
                                    temp.goodsCreateBy = question.createdBy;
                                    temp.save(callback);
                                }
                            })
                        } else {
                            var msg = {
                                "message": "已经举报过了"
                            };
                            callback(msg, null);
                        }
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   chenf  20170821   end   */
/**
 * ==================================回答======================================
 */

/**
 * 回答问题
 */
exports.postReplyService = function (token, questionId, input, callback) {
    var nickName;

    async.waterfall([
        function (callbackInner) {
            Users.findOne({'_id': toolUtil.getUserObjIdByToken(token)}, function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == undefined) {
                var err = {
                    "message": 'User not found'
                };
                callback(err, null);
            } else {
                nickName = result.nickName;
                if (nickName == undefined) {
                    nickName = '有人'
                }
                var desc = input.replies.replyDesc.replace(/[\r\n]/g, "").trim();
                var rep = {
                    'replyDesc': desc,
                    'replyTo': input.replies.replyTo,
                    'repliedBy': result._id
                };
                Question.update({_id: questionId}, {$push: {'replies': rep}}).exec(function (err, result) {
                    callbackInner(null, result);
                    ugcIndex.update({ugcId: questionId}, {lastReply: new Date()}, function (err, result) {
                    });
                });
            }
        },
        function (result, callbackInner) {
            Question.findOne({
                _id: questionId,
                'isValid': true
            }).populate('createdBy', '_id community').exec(function (err, question) {
                if (question == null) {
                    var msg = {
                        "message": '这个问题已被删除'
                    };
                    callback(msg, null);
                } else {
                    Dic.findOne({'value': '全部', 'category': '02'}, '_id', function (err, res) {
                        QuestionAndReplyCount.findOne({
                            'community': question.community,
                            'tag': res
                        }, '', function (err, qc) {
                            if (qc == null) {
                                var temp = new QuestionAndReplyCount();
                                temp.replyCount = 1;
                                temp.community = question.community;
                                temp.tag = res;
                                temp.save();
                            } else {
                                qc.replyCount += 1;
                                qc.save();
                            }
                        })
                    });
                    callbackInner(null, question);
                }
            });
        },
        function (question, callbackInner) {

            //统计回答
            if (question.tag != null) {
                question.tag.forEach(function (result) {
                    QuestionReplyStatistics.findOne({
                        'community': question.community,
                        'user': toolUtil.getUserObjIdByToken(token),
                        'tag': result
                    }, 'replyCount', function (err, res) {
                        if (res == null) {
                            var temp = new QuestionReplyStatistics();
                            temp.community = question.community;
                            temp.user = toolUtil.getUserObjIdByToken(token);
                            temp.tag = result;
                            temp.replyCount = 1;
                            temp.save();
                        } else {
                            var count = res.replyCount + 1;
                            QuestionReplyStatistics.update({
                                'community': question.community,
                                'user': toolUtil.getUserObjIdByToken(token),
                                'tag': result
                            }, {'replyCount': count}, function (err, result) {
                            })
                        }
                    });


                    QuestionAndReplyCount.findOne({
                        'community': question.community,
                        'tag': result
                    }, '', function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.replyCount = 1;
                            temp.community = question.community;
                            temp.tag = result;
                            temp.save();
                        } else {
                            qc.replyCount += 1;
                            qc.save();
                        }
                    })

                })
            }
            if (input.replies.replyTo != undefined) {
                Users.findOne({
                    _id: input.replies.replyTo,
                    community: question.community
                }, function (err, result) {
                    if (result != null) {
                        var temp = new SystemMessage();
                        temp.toUser = input.replies.replyTo;
                        temp.content.questionDesc = question.desc;
                        temp.content.replyDesc = input.replies.replyDesc;
                        temp.content.title = nickName;
                        temp.content.contentId = question._id;
                        temp.content.contentType = 'myReply';
                        temp.content.questionCreatedBy = question.createdBy._id;
                        temp.category = 'question';
                        temp.fromUser = toolUtil.getUserObjIdByToken(token);
                        temp.save();

                        //个推
                        var content = {
                            type: 1,
                            flag: 1,
                            openType: 1,
                            contentId: question._id,
                            createdBy: question.createdBy._id,
                            desc: nickName + '回复了你的回复'
                        };
                        var pushData = {
                            uList: [input.replies.replyTo],
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                });
            }
            var communityId = question.community + '';
            if (communityId == question.createdBy.community && toolUtil.getUserObjIdByToken(token) != question.createdBy._id && input.replies.replyTo == undefined) {
                var temp = new SystemMessage();
                temp.toUser = question.createdBy._id;
                temp.content.questionDesc = question.desc;
                temp.content.replyDesc = input.replies.replyDesc;
                temp.content.title = nickName;
                temp.content.contentId = question._id;
                temp.content.contentType = 'myQuestion';
                temp.content.questionCreatedBy = question.createdBy._id;
                temp.category = 'question';
                temp.fromUser = toolUtil.getUserObjIdByToken(token);
                temp.save();
            }

            if (input.replies.replyTo == undefined) {
                UserFollowups.find({'question': questionId}, 'user').populate('user', '_id community').exec(function (err, result) {
                    if (result == undefined) {
                        callbackInner(null, question);
                    } else {
                        callbackInner(null, question);

                        var users = [];
                        result.forEach(function (userId) {
                            var communityId = question.community + '';
                            if (userId.user.community == communityId && userId.user._id != toolUtil.getUserObjIdByToken(token)) {
                                var temp = new SystemMessage();
                                temp.toUser = userId.user._id;
                                temp.content.questionDesc = question.desc;
                                temp.content.replyDesc = input.replies.replyDesc;
                                temp.content.title = nickName;
                                temp.content.contentId = question._id;
                                temp.content.contentType = 'myFollowup';
                                temp.content.questionCreatedBy = question.createdBy._id;
                                temp.category = 'question';
                                temp.fromUser = toolUtil.getUserObjIdByToken(token);
                                temp.save();

                                users.push(userId.user._id);
                            }
                        });

                        //个推
                        var content = {
                            openType: 1,
                            flag: 1,
                            contentId: question._id,
                            createdBy: question.createdBy._id,
                            desc: nickName + '回复你的收藏',
                            type: 0
                        };
                        var pushData = {
                            uList: users,
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                })
            } else {
                callbackInner(null, question);
            }
        },
        function (question, callbackInner) {

            if (question.category != null)
                redisClient.hincrby('q:count:' + question.community, question.category + 'ReplyCount', 1);

            if (input.replies.replyTo == undefined) {
                var communityId = question.community + '';
                if (communityId == question.createdBy.community && toolUtil.getUserObjIdByToken(token) != question.createdBy._id) {

                    //个推
                    var content = {
                        type: 1,
                        openType: 1,
                        flag: 1,
                        contentId: question._id,
                        createdBy: question.createdBy._id,
                        desc: nickName + '回复了你的发布'
                    };
                    var pushData = {
                        uList: [question.createdBy._id],
                        content: content,
                        type: 'user'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);

                }
            }
            Question.findOne({_id: questionId, 'isValid': true}).exec(function (err, result) {
                callbackInner(err, result);

                ugcReply.findOne({
                    ugcId: result._id,
                    repliedBy: toolUtil.getUserObjIdByToken(token)
                }, function (err, data) {
                    if (data == null) {
                        var temp = new ugcReply();
                        temp.ugcId = result._id;
                        temp.ugcReply = [{
                            replyId: result.replies[result.replies.length - 1]._id
                        }];
                        temp.category = result.category;
                        temp.community = result.community;
                        temp.createdBy = result.createdBy;
                        temp.repliedBy = toolUtil.getUserObjIdByToken(token);
                        temp.save();
                    } else {
                        var temp = {
                            replyId: result.replies[result.replies.length - 1]._id
                        };
                        data.ugcReply.push(temp);
                        data.lastReply = new Date();
                        data.save()
                    }

                })
            });
            Question.update({_id: questionId}, {dateLastModified: new Date()}).exec(function (err, result) {
            });
        }
    ], function (err, result) {
        callback(err, result);
    });
};

/**
 * 回复新接口
 * @param token
 * @param input
 * @param questionId
 * @param callback
 */
exports.postReplyNewService = function (token, questionId, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            if (user._id == input.replyTo) {
                input.replyTo = null;
            }
            var question;
            var replyId;
            async.series([
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        if (result == null) {
                            var msg = {
                                message: '问题不存在或已被删除'
                            };
                            logger.info('callbackInner---1-1');
                            callbackInner(msg, null);
                        } else {
                            question = result;
                            question._doc['huanxinName'] = user.huanxinUserName;
                            callbackInner(err, question);
                        }
                    })
                },
                function (callbackInner) {
                    var desc = input.replyDesc.replace(/[\r\n]{2,}/g, "\n").trim();
                    var rep = {
                        'replyDesc': desc,
                        'replyTo': input.replyTo,
                        'repliedBy': user._id,
                        'community': user.community._id,
                        'images': input.images
                    };
                    Question.update({_id: questionId}, {$push: {'replies': rep}}).exec(callbackInner);
                },
                function (callbackInner) {
                    Question.update({_id: questionId}, {dateLastModified: new Date()}).exec(function (err, result) {
                    });
                    ugcIndex.update({ugcId: questionId}, {lastReply: new Date()}, callbackInner);
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        replyId = result.replies[result.replies.length - 1]._id;
                        callbackInner()
                    });
                },
                function (callbackInner) {
                    //统计回答
                    if (question.tag != null && question.tag.length > 0) {
                        async.each(question.tag, function (result, c1) {
                            QuestionReplyStatistics.findOne({
                                'community': question.community,
                                'user': user._id,
                                'tag': result
                            }, 'replyCount', function (err, res) {
                                if (res == null) {
                                    var temp = new QuestionReplyStatistics();
                                    temp.community = question.community;
                                    temp.user = user._id;
                                    temp.tag = result;
                                    temp.replyCount = 1;
                                    temp.save(c1);
                                } else {
                                    var count = res.replyCount + 1;
                                    QuestionReplyStatistics.update({
                                        'community': question.community,
                                        'user': user._id,
                                        'tag': result
                                    }, {'replyCount': count}, c1)
                                }
                            });
                        }, callbackInner)
                    } else {
                        callbackInner();
                    }
                },
                function (callbackInner) {

                    callbackInner();
                },
                function (callbackInner) {

                    callbackInner();
                },
                function (callbackInner) {

                    callbackInner()
                },
                function (callbackInner) {
                    if (question.category != null)
                        redisClient.hincrby('q:count:' + question.community, question.category + 'ReplyCount', 1);
                    callbackInner();
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        callbackInner(err, result);

                        //ugcReply.findOne({ugcId: result._id, repliedBy: user._id}, function (err, data) {
                        //    if (data == null) {
                        var temp = new ugcReply();
                        temp.ugcId = result._id;
                        temp.replyId = result.replies[result.replies.length - 1]._id;
                        //temp.ugcReply = [{
                        //    replyId: result.replies[result.replies.length - 1]._id
                        //}];
                        temp.category = result.category;
                        temp.community = result.community;
                        temp.createdBy = result.createdBy;
                        temp.aroundCommunity = result.aroundCommunity;
                        temp.repliedBy = user._id;
                        temp.save();
                        //} else {
                        //    var temp = {
                        //        replyId: result.replies[result.replies.length - 1]._id
                        //    };
                        //    data.ugcReply.push(temp);
                        //    data.lastReply = new Date();
                        //    data.save()
                        //}
                        //})
                    }).populate('replies.repliedBy', '_id nickName images userType authenticationStatus roomUnit').populate('replies.replyTo', '_id nickName images').populate('replies.community', 'communityName')
                }
            ], callback)
        }
    })
};

exports.replyAtService = function (question, replyId, uList, category, token, replyDesc) {
    async.series([
        function (callbackInner) {
            var temp = new replyAt();
            temp.replyId = replyId + '';
            temp.ugcId = question._id;
            temp.category = category;
            temp.createdBy = question.createdBy;
            temp.uList = uList;
            temp.save(callbackInner);
        },
        function (callbackInner) {

            logger.info(uList);

            async.eachSeries(uList, function (uId, c1) {
                Users.findOne({_id: uId}, 'huanxinUserName community', function (err, result) {
                    if (result != null) {
                        if (result.huanxinUserName == '66customerservice') {
                            var temp = new replyAtService();
                            temp.ugcId = question._id;
                            temp.category = category;
                            temp.atUser = token;
                            temp.community = result.community;
                            temp.content = replyDesc;
                            temp.replyId = replyId;
                            temp.save(c1)

                        } else {
                            recentContact.findOne({
                                userHuanxin: question._doc.huanxinName,
                                otherHuanxin: result.huanxinUserName
                            }, function (err, data) {
                                if (data != null) {
                                    data.time = new Date();
                                    data.save(c1);
                                } else {
                                    var temp = new recentContact();
                                    temp.userHuanxin = question._doc.huanxinName;
                                    temp.otherHuanxin = result.huanxinUserName;
                                    temp.time = new Date();
                                    temp.save(c1);
                                }
                            })
                        }
                    } else {
                        c1();
                    }
                })
            }, callbackInner);
        }
    ]);
};


exports.thankReplyService = function (questionId, replyId, replyBy, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReplyThank.findOne({'user': user._id, 'reply': replyId}, function (err, result) {
                if (result != null) {
                    var msg = {
                        "message": "你已经感谢过了"
                    };
                    callback(msg, null);
                } else {
                    Question.findOne({
                        _id: questionId,
                        'isValid': true
                    }).populate('createdBy', '_id nickName').exec(function (err, result) {
                        var tempT = new QuestionReplyThank();
                        tempT.user = user._id;
                        tempT.reply = replyId;
                        tempT.replyBy = replyBy;
                        tempT.save();

                        var nickName = user.nickName;
                        if (nickName == undefined) {
                            nickName = ''
                        }

                        var content = {
                            type: 2,
                            openType: 1,
                            flag: 1,
                            contentId: questionId,
                            createdBy: result.createdBy._id,
                            desc: '你被' + nickName + '感谢咯~'
                        };
                        var pushData = {
                            uList: [replyBy],
                            content: content,
                            type: 'user',
                            pushApns: 'no'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);


                        callback(err, result);

                        var replies = result.replies;
                        if (replies != null) {
                            replies.forEach(function (reply) {
                                if (reply._id == replyId) {

                                    toolUtil.changeUserStatistics(reply.repliedBy, reply.community, 'thankedReply', 1);


                                    var temp = new SystemMessage();
                                    temp.toUser = reply.repliedBy;
                                    temp.content.questionDesc = reply.replyDesc;
                                    temp.content.replyDesc = '感谢了你';
                                    temp.content.title = nickName;
                                    temp.content.contentId = result._id;
                                    temp.content.contentType = 'myThank';
                                    temp.content.questionCreatedBy = result.createdBy._id;
                                    temp.category = 'question';
                                    temp.fromUser = user._id;
                                    temp.fromCommunity = user.community._id;
                                    temp.toCommunity = reply.community;
                                    temp.save(function (err, re) {
                                        if (err) {
                                            logger.error('thankReply-----' + err);
                                        }
                                    });
                                }
                            })
                        }
                    });
                }
            });
        }
    });
};

exports.getCategoryQuestionCountService = function (token, category, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            if (category == 'all') {
                var questionCount = 0;
                var replyCount = 0;
                redisClient.hkeys('q:count:' + user.community._id, function (err, fields) {
                    async.each(fields, function (field, callbackInner) {
                        redisClient.hget('q:count:' + user.community._id, field, function (err, count) {
                            if (field.indexOf('QuestionCount') != -1) {
                                questionCount += Number(count);
                            } else {
                                replyCount += Number(count);
                            }
                            callbackInner();
                        });
                    }, function (err) {
                        var data = {
                            questionCount: questionCount,
                            replyCount: replyCount
                        };
                        callback(err, data);
                    })
                });
            } else {
                var fields = [category + 'QuestionCount', category + 'ReplyCount'];
                redisClient.hmget('q:count:' + user.community._id, fields, function (err, count) {
                    if (count[0] == null && count[1] == null) {

                        if (category != 'neighbourActivity') {
                            Question.find({
                                category: category,
                                community: user.community._id,
                                isValid: true
                            }, '_id replies', function (err, results) {
                                var replyCount = 0;
                                var questionCount = 0;
                                if (results != null) {
                                    questionCount = results.length;
                                    results.forEach(function (question) {
                                        if (question.replies != null) {
                                            replyCount += question.replies.length;
                                        }
                                    });
                                }

                                redisClient.hincrby('q:count:' + user.community._id, category + 'QuestionCount', questionCount);
                                redisClient.hincrby('q:count:' + user.community._id, category + 'ReplyCount', replyCount);

                                var data = {
                                    questionCount: questionCount,
                                    replyCount: replyCount
                                };
                                callback(err, data);
                            })
                        } else {
                            neighbourActivity.find({
                                community: user.community._id,
                                isValid: true
                            }, '_id replies', function (err, results) {
                                var replyCount = 0;
                                var questionCount = 0;
                                if (results != null) {
                                    questionCount = results.length;
                                    results.forEach(function (question) {
                                        if (question.replies != null) {
                                            replyCount += question.replies.length;
                                        }
                                    });
                                }

                                redisClient.hincrby('q:count:' + user.community._id, category + 'QuestionCount', questionCount);
                                redisClient.hincrby('q:count:' + user.community._id, category + 'ReplyCount', replyCount);

                                var data = {
                                    questionCount: questionCount,
                                    replyCount: replyCount
                                };
                                callback(err, data);
                            })
                        }
                    } else {
                        var data = {
                            questionCount: Number(count[0]),
                            replyCount: Number(count[1])
                        };
                        callback(err, data);
                    }
                });
            }
        }
    });
};

/**
 * 获取小区标签问题和回复数量
 * @param token
 * @param tagId
 * @param callback
 */
exports.getCommunityQuestionAndReplyCountService = function (token, tagId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionAndReplyCount.findOne({
                'community': user.community._id,
                'tag': tagId
            }, '-_id questionCount replyCount', function (err, result) {
                if (result != null) {
                    callback(err, result);
                } else {
                    Dic.findOne({_id: tagId}, 'value', function (err, value) {

                        if (value != null) {
                            if (value.value == '全部') {
                                Question.find({
                                    'community': user.community._id,
                                    'isValid': true
                                }, '_id replies', function (err, results) {
                                    var replyCount = 0;
                                    var questionCount = results.length;
                                    if (results != null) {
                                        results.forEach(function (question) {
                                            if (question.replies != null) {
                                                replyCount += question.replies.length;
                                            }
                                        });
                                    }
                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = questionCount;
                                    temp.replyCount = replyCount;
                                    temp.tag = tagId;
                                    temp.community = user.community._id;
                                    temp.save();
                                    var re = {
                                        "replyCount": replyCount,
                                        "questionCount": questionCount
                                    };
                                    callback(err, re);
                                })
                            } else if (value.value == '推荐') {
                                Question.find({
                                    'community': user.community._id,
                                    'isValid': true,
                                    recommend: true
                                }, '_id replies', function (err, results) {
                                    var replyCount = 0;
                                    var questionCount = results.length;
                                    if (results != null) {
                                        results.forEach(function (question) {
                                            if (question.replies != null) {
                                                replyCount += question.replies.length;
                                            }
                                        });
                                    }

                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = questionCount;
                                    temp.replyCount = replyCount;
                                    temp.tag = tagId;
                                    temp.community = user.community._id;
                                    temp.save();
                                    var re = {
                                        "replyCount": replyCount,
                                        "questionCount": questionCount
                                    };
                                    callback(err, re);
                                })
                            } else {
                                Question.find({
                                    'community': user.community._id,
                                    'tag': tagId,
                                    'isValid': true
                                }, '_id replies', function (err, results) {
                                    var replyCount = 0;
                                    var questionCount = results.length;
                                    if (results != null) {
                                        results.forEach(function (question) {
                                            if (question.replies != null) {
                                                replyCount += question.replies.length;
                                            }
                                        });
                                    }
                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = questionCount;
                                    temp.replyCount = replyCount;
                                    temp.tag = tagId;
                                    temp.community = user.community._id;
                                    temp.save();
                                    var re = {
                                        "replyCount": replyCount,
                                        "questionCount": questionCount
                                    };
                                    callback(err, re);
                                })
                            }
                        } else {
                            var msg = {
                                "message": "No such tag"
                            };
                            callback(msg, null);
                        }
                    });
                }
            });
        }
    });
};

/**
 *上传回答图片
 */
exports.setImagesToReply = function (questionId, replyId, images, callback) {
    Question.update({
        _id: questionId,
        'replies._id': replyId
    }, {$pushAll: {'replies.$.images': images}}, callback);
};

/**
 * 修改回答
 */
exports.updateReplyService = function (questionId, replyId, input, callback) {
    Question.update({
        _id: questionId,
        'replies._id': replyId
    }, {'replies.$.replyDesc': input.replies.replyDesc}).exec(callback);
};

/**
 * 删除回答
 */
exports.deleteReplyService = function (token, questionId, replyId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            async.series([
                function (callbackInner) {
                    Question.update({_id: questionId}, {
                        $pull: {
                            replies: {
                                _id: replyId,
                                repliedBy: user._id
                            }
                        }
                    }).exec(callbackInner);
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, 'category community replies createdBy', function (err, result) {
                        if (result.category != null)
                            redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -1);
                        callbackInner(null, result);
                    })
                }
            ], function (err, result) {
                callback(err, result);

                replyIndex.findOne({replyId: replyId}, function (err, result) {
                    toolUtil.changeUserStatistics(result.repliedBy, result.community, 'questionReply', -1);
                    replyIndex.remove({replyId: replyId}, null);
                });
            })
        }
    })
};

/**
 * 删除回答图片
 */
exports.deleteReplyImagesService = function (questionId, replyId, images, callback) {

    Question.findOne({_id: questionId, 'isValid': true}).exec(function (err, result) {
        if (result == undefined) {
            var err = {
                "message": 'Question not found'
            };
            callback(err, null);
        } else {
            var replies = result.replies;
            var index;
            for (var i = 0; i < replies.length; i++) {
                if (replyId == replies[i]._id) {
                    index = i;
                }
            }
            var images1 = replies[index].images;
            var images2 = images.replies.images;

            for (var i = 0; i < images1.length; i++) {
                for (var j = 0; j < images2.length; j++) {
                    if (images1[i]._doc.imageURL == images2[j]) {
                        result.replies.id(replyId).images.id(images1[i]._id).isValid = false;
                        result.save(callback);
                    }
                }
            }
        }
    })
};

/**
 * 采纳回答
 */
exports.adoptReplyService = function (token, questionId, replyId, callback) {

    var replyBy, replyCommunity;
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            Question.findOne({
                _id: questionId,
                isValid: true,
                status: '未解决'
            }).populate('createdBy', '_id nickName').exec(function (err, result) {
                if (result == null || result.replies == null) {
                    var msg = {
                        "message": '采纳失败'
                    };
                    callback(msg, null);
                } else {

                    var isAdopt = false;
                    result.replies.forEach(function (reply) {
                        if (reply.replyStatus == '已采纳') {
                            var msg = {
                                "message": '已有采纳回复'
                            };
                            isAdopt = true;
                            callback(msg, null);
                        }
                    });

                    if (!isAdopt) {
                        Question.update({_id: questionId, 'replies._id': replyId}, {
                            'status': '已解决',
                            'replies.$.replyStatus': '已采纳'
                        }).exec();

                        questionService.moveReplyToTopService(questionId, replyId);

                        replyIndex.update({replyId: replyId}, {replyStatus: '已采纳'}).exec();

                        result.replies.forEach(function (reply) {
                            if (reply._id == replyId) {
                                replyBy = reply.repliedBy;
                                replyCommunity = reply.community;
                                AdoptedCount.findOne({
                                    community: result.community,
                                    user: reply.repliedBy
                                }, function (err, adopt) {
                                    if (adopt == null) {
                                        var temp = new AdoptedCount();
                                        temp.community = result.community;
                                        temp.user = reply.repliedBy;
                                        temp.adoptedCount = 1;
                                        temp.save()
                                    } else {
                                        AdoptedCount.update({
                                            community: result.community,
                                            user: reply.repliedBy
                                        }, {adoptedCount: adopt.adoptedCount + 1}).exec()
                                    }
                                });


                                var temp = new SystemMessage();
                                temp.toUser = reply.repliedBy;
                                temp.content.questionDesc = result.desc;
                                temp.content.replyDesc = '采纳了你的好意见';
                                temp.content.title = result.createdBy.nickName;
                                temp.content.contentId = result._id;
                                temp.content.contentType = 'myAdopt';
                                temp.content.questionCreatedBy = result.createdBy._id;
                                temp.category = 'question';
                                temp.fromUser = result.createdBy._id;
                                temp.fromCommunity = user.community._id;
                                temp.toCommunity = reply.community;
                                temp.save(function (err, re) {
                                });


                                var pushMsg = result.createdBy.nickName + '采纳了你的好意见，离中国好邻居又近了一步！';
                                if (result.score > 0) {
                                    pushMsg = result.createdBy.nickName + '采纳了你的好意见，诱人悬赏奉上啦！';
                                }

                                var content = {
                                    type: 1,
                                    openType: 1,
                                    flag: 1,
                                    contentId: questionId,
                                    createdBy: result.createdBy._id,
                                    desc: pushMsg
                                };
                                var pushData = {
                                    uList: [reply.repliedBy],
                                    content: content,
                                    type: 'user'
                                };
                                toolUtil.putMessageGetuiPushMQ(pushData);
                            }
                        });

                        var data = {
                            replyBy: replyBy,
                            replyCommunity: replyCommunity,
                            category: result.category
                        };
                        if (result.score != null) {
                            data.score = result.score;
                        }

                        callback(null, data);
                    }
                }
            })
        }
    });
};

/**
 * ==================================投票==================================
 */

/**
 * 创建投票
 */
exports.createPollService = function (token, input, callback) {
    async.waterfall([
        function (callbackInner) {
            Users.findOne({'_id': toolUtil.getUserObjIdByToken(token)}, function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == undefined) {
                var err = {
                    "message": 'User not found'
                };
                callback(err, null);
            } else {
                var temp = new Question();
                temp.category = input.category;
                temp.desc = input.desc;
                temp.status = '进行中';
                temp.pollOptions = input.pollOptions;
                temp.createdBy = result._id;
                temp.community = result.community;
                temp.save(callbackInner);
            }
        }
    ], callback);
};


/**
 * 修改投票
 */
exports.updatePollService = function (pollId, input, callback) {
    Question.update({_id: pollId}, input).exec(callback);
};


/**
 * 投票
 */
exports.doPollService = function (pollId, input, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
            if (err) {
                callback(err, null);
            } else {
                async.waterfall([
                    function (callbackInner) {
                        Question.findOne({_id: pollId, 'isValid': true}, function (err, result) {
                            if (result == undefined || result == null) {
                                err = {
                                    "message": 'Poll not found'
                                };
                                callback(err, null);
                            } else {
                                if (result.pollUserList != null && result.pollUserList.indexOf(user._id) != -1) {
                                    err = {
                                        "message": 'You have voted'
                                    };
                                    callback(err, null);
                                } else {
                                    callbackInner(null, result);
                                }
                            }
                        })
                    },
                    function (result, callbackInner) {
                        result.pollOptions.forEach(function (poll) {
                                if (poll.optionLabel == input.pollOptions.optionLabel) {
                                    var count = result.pollOptions.id(poll._id).optionCount;
                                    if (count == undefined) {
                                        result.pollOptions.id(poll._id).optionCount = 1;
                                    } else {
                                        result.pollOptions.id(poll._id).optionCount++;
                                    }

                                    result.save(function (err, result) {
                                            if (err) {
                                                callback(err, null);
                                            } else {
                                                callbackInner(null, null)
                                            }
                                        }
                                    )
                                }
                            }
                        )
                    },
                    function (result, callbackInner) {
                        Question.update({_id: pollId}, {'$push': {'pollUserList': user._id}}, function (err, result) {
                            callbackInner(null, null);
                        })
                    },
                    function (result, callbackInner) {
                        Question.findOne({_id: pollId, 'isValid': true}, 'pollOptions', function (err, result) {
                            if (err) {
                                callback(err, null);
                            } else {
                                result._id = undefined;
                                callback(null, result);
                            }
                        })
                    }
                ], callback);
            }
        }
    )
}
;

/**
 * 关闭投票
 */
exports.closePollService = function (pollId, callback) {
    Question.update({_id: pollId}, {'status': '已关闭'}).exec(callback);
};

/**
 * 获取提问详情
 */
exports.getDetailOfQuestionOrPollService = function (token, id, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Question.findOne({
                _id: id,
                'isValid': true
            }, '_id desc community category browserCount status tag images.imageURL images._id replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.replyType replies.displayOrder replies.dateReplied replies.repliedBy replies.replyTo pollOptions dateCreated createdBy')
                .populate('tag', 'category value _id').populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus').populate('replies.repliedBy', '_id nickName images userType authenticationStatus').populate('replies.replyTo', '_id nickName images').exec(function (err, result) {
                    if (result == null) {
                        var msg = {
                            "message": "这个问题已被删除"
                        };
                        callback(msg, null);
                    } else {
                        result.replies.sort(function (a, b) {
                            if (a.displayOrder == undefined) {
                                a.displayOrder = 0;
                            }
                            if (b.displayOrder == undefined) {
                                b.displayOrder = 0;
                            }
                            if (a.displayOrder > b.displayOrder) {
                                return -1
                            } else if (a.displayOrder < b.displayOrder) {
                                return 1
                            } else {
                                return a.dateReplied - b.dateReplied
                            }
                        });

                        var browserCount;
                        if (result.browserCount == null) {
                            browserCount = 0;
                        } else {
                            browserCount = result.browserCount + 1;
                        }
                        result.browserCount = browserCount;

                        if (result.tag == null || result.tag.length == 0) {
                            result.tag = undefined;
                        }

                        async.each(result.replies, function (reply, callback) {
                            if (reply.replyTo == null) {
                                reply.replyTo = undefined;
                            }
                            reply.displayOrder = undefined;

                            QuestionReplyPraise.find({'reply': reply._id}, '', function (err, resPra) {
                                if (resPra == null) {
                                    reply._doc['praiseCount'] = 0
                                } else {
                                    reply._doc['praiseCount'] = resPra.length;
                                    reply._doc['isPraise'] = 'No';
                                    resPra.forEach(function (res) {
                                        if (res.user == user._id) {
                                            reply._doc['isPraise'] = 'Yes'
                                        }
                                    });
                                }
                                QuestionReplyThank.findOne({
                                    'reply': reply._id,
                                    'user': result.createdBy._id
                                }, function (err, result) {
                                    if (result == null) {
                                        reply._doc['isThank'] = 'No'
                                    } else {
                                        reply._doc['isThank'] = 'Yes'
                                    }
                                    callback();
                                });
                            });
                        }, function (err) {
                            if (err) {
                                callback(err, null);
                            } else {
                                Question.update({_id: id}, {'browserCount': browserCount}, function (err, re) {
                                    UserFollowups.findOne({
                                        'user': user._id,
                                        'question': id
                                    }, function (err, userFollowup) {
                                        if (err || userFollowup == null) {
                                            result._doc['followup'] = 'No'
                                        } else {
                                            result._doc['followup'] = 'Yes'
                                        }
                                        callback(err, result);
                                    });
                                });
                            }
                        });
                    }
                });
        }
    })
};

exports.getDetailOfQuestionService = function (token, id, vCode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Question.findOne({
                _id: id,
                'isValid': true
                //$or: [{isShow: null}, {createdBy: user._id, isShow: -1}]
            }, '_id desc community category browserCount status tag images.imageURL images._id  dateCreated createdBy praiseCount score topicId level')
                .populate('tag', 'category value _id').populate('community', '_id communityName location').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit userRole exp').exec(function (err, result) {
                    if (result == null) {
                        var msg = {
                            "message": "这个问题已被删除"
                        };
                        callback(msg, null);
                    } else {

                        var browserCount;
                        if (result.browserCount == null) {
                            browserCount = 0;
                        } else {
                            browserCount = result.browserCount + 1;
                        }

                        var distance = geolib.getDistance(
                            {latitude: user.community.location.latitude, longitude: user.community.location.longitude},
                            {
                                latitude: result.community.location.latitude,
                                longitude: result.community.location.longitude
                            }
                        );
                        if (distance > 0)
                            result._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';

                        if (result.topicId != null) {
                            result._doc.topicUrl = h5Host + '/app/topic/index.html?tid=' + result.topicId;
                        }

                        result.browserCount = browserCount;
                        result._doc['browserCountStr'] = toolUtil.transformNumber(browserCount);

                        if (result.tag == null || result.tag.length == 0) {
                            result.tag = undefined;
                        }

                        var isOtherCommunity = user.community._id != result.community._id + '';

                        if (result.createdBy.roomUnit != null && result.createdBy.roomUnit != '')
                            result.createdBy._doc.roomUnit = Number(vCode) >= 106000 && !isNaN(result.createdBy.roomUnit) ? result.createdBy.roomUnit + '单元' : result.createdBy.roomUnit;

                        if ((result.createdBy.showUnit != null && !result.createdBy.showUnit) || isOtherCommunity) {
                            result.createdBy.roomUnit = undefined;
                        }
                        result.createdBy.showUnit = undefined;

                        result.createdBy._doc.level = toolUtil.getUserLevel(result.createdBy.exp);

                        result._doc.praiseCount = toolUtil.transformNumber(result.praiseCount);

                        result._doc['shareData'] = shareService.shareDataService(result.community.communityName + "的" + questionCategory[result.category],
                            result.desc, result.images, 'question');

                        result._doc.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';

                        async.parallel([
                            function (callbackInner) {          //更新浏览量
                                Question.update({_id: id}, {'browserCount': browserCount}, callbackInner)
                            },
                            function (callbackInner) {          //是否收藏此问题
                                UserFollowups.findOne({user: user._id, question: id}, function (err, userFollowup) {
                                    if (err || userFollowup == null) {
                                        result._doc['followup'] = 'No'
                                    } else {
                                        result._doc['followup'] = 'Yes'
                                    }
                                    callbackInner();
                                })
                            },
                            function (callbackInner) {          //是否点赞
                                questionPraise.findOne({question: result._id, user: user._id}, function (err, praise) {
                                    result._doc['isPraise'] = praise != null;
                                    callbackInner();
                                });
                            },
                            function (callbackInner) {          //最近8个点赞人信息
                                questionPraise.find({question: result._id}).sort('-dateCreated').limit(8)
                                    .populate('user', 'nickName images userType authenticationStatus')
                                    .exec(function (err, praises) {
                                        result._doc['praiseUsers'] = [];
                                        if (praises != null) {
                                            praises.forEach(function (praise) {
                                                if (praise.user != null)result._doc.praiseUsers.push(praise.user);
                                            })
                                        }
                                        callbackInner();
                                    })
                            }
                        ], function (err) {
                            callback(null, result);
                        });
                    }
                });
        }
    });
};


exports.getQuestionPartDetailService = function (token, questionId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var data = {};

            async.parallel([
                function (callbackInner) {
                    Question.findOne({
                        _id: questionId,
                        isValid: true
                        //$or: [{isShow: null}, {createdBy: user._id, isShow: -1}]
                    }, 'community category desc images', function (err, result) {
                        if (result != null) {
                            data.category = result.category;
                            data.shareData = shareService.shareDataService(result.community.communityName + "的" + questionCategory[result.category], result.desc, result.images, 'question');
                            callbackInner();
                        } else {
                            // callbackInner({message: '这个问题已被删除'}, null);
                            callbackInner(ErrorMessage.MSG_Q_DELETED, null);
                        }
                    }).populate('community', 'communityName');
                },
                function (callbackInner) {          //更新浏览量
                    Question.update({_id: questionId}, {$inc: {browserCount: 1}}, callbackInner)
                },
                function (callbackInner) {          //是否收藏此问题
                    UserFollowups.findOne({user: user._id, question: questionId}, function (err, userFollowup) {
                        if (err || userFollowup == null) {
                            data['followup'] = 'No'
                        } else {
                            data['followup'] = 'Yes'
                        }
                        callbackInner();
                    })
                },
                function (callbackInner) {          //是否点赞
                    questionPraise.findOne({question: questionId, user: user._id}, function (err, praise) {
                        data['isPraise'] = praise != null;
                        callbackInner();
                    });
                },
                function (callbackInner) {          //最近8个点赞人信息
                    questionPraise.find({question: questionId}).sort('-dateCreated').limit(8)
                        .populate('user', 'nickName images userType authenticationStatus')
                        .exec(function (err, praises) {
                            data['praiseUsers'] = [];
                            if (praises != null) {
                                praises.forEach(function (praise) {
                                    if (praise.user != null)data.praiseUsers.push(praise.user);
                                })
                            }
                            callbackInner();
                        })
                }
            ], function (err) {
                callback(err, data);
            });
        }
    })
};


exports.getDetailReplyOfQuestionService = function (page, token, id, vcode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var data = [];
            Question.findOne({
                _id: id,
                'isValid': true
            }, 'createdBy replies.community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.replyType replies.displayOrder replies.dateReplied replies.repliedBy replies.replyTo')
                .populate('createdBy', '_id nickName images userType authenticationStatus')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus showUnit roomUnit userRole')
                .populate('replies.replyTo', '_id nickName images')
                .populate('replies.community', 'communityName')
                .exec(function (err, result) {
                    if (result == null || result.replies == null) {
                        callback(null, data);
                    } else {
                        result.replies.sort(function (a, b) {
                            if (a.displayOrder == undefined) {
                                a.displayOrder = 0;
                            }
                            if (b.displayOrder == undefined) {
                                b.displayOrder = 0;
                            }
                            if (a.displayOrder > b.displayOrder) {
                                return -1
                            } else if (a.displayOrder < b.displayOrder) {
                                return 1
                            } else {
                                return a.dateReplied - b.dateReplied
                            }
                        });

                        async.each(result.replies, function (reply, callback1) {


                            if (reply.community != null) {
                                var isOtherCommunity = user.community._id != reply.community._id + '';
                            }

                            if (reply.repliedBy.roomUnit != null && reply.repliedBy.roomUnit != '')
                                reply.repliedBy._doc.roomUnit = Number(vcode) >= 106000 && !isNaN(reply.repliedBy.roomUnit) ? reply.repliedBy.roomUnit + '单元' : reply.repliedBy.roomUnit;


                            if ((reply.repliedBy.showUnit != null && !reply.repliedBy.showUnit) || isOtherCommunity) {
                                reply.repliedBy.roomUnit = undefined;
                            }
                            reply.repliedBy.showUnit = undefined;

                            if (reply.replyTo == null) {
                                reply.replyTo = undefined;
                            }
                            reply.displayOrder = undefined;


                            QuestionReplyPraise.find({'reply': reply._id}, '', function (err, resPra) {
                                if (resPra == null) {
                                    reply._doc['praiseCount'] = 0
                                } else {
                                    reply._doc['praiseCount'] = resPra.length;
                                    reply._doc['isPraise'] = 'No';
                                    resPra.forEach(function (res) {
                                        if (res.user == user._id) {
                                            reply._doc['isPraise'] = 'Yes'
                                        }
                                    });
                                }
                                QuestionReplyThank.findOne({
                                    'reply': reply._doc._id,
                                    'user': result.createdBy._id
                                }, function (err, result) {
                                    if (result == null) {
                                        reply._doc['isThank'] = 'No'
                                    } else {
                                        reply._doc['isThank'] = 'Yes'
                                    }

                                    if (reply.replyDesc.indexOf(atFlag) != -1) {

                                        replyAt.findOne({replyId: reply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                if (vcode < 1500) {
                                                    at.uList.forEach(function (temp, i) {
                                                        reply.replyDesc = reply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                    });
                                                } else {
                                                    reply._doc['uList'] = at.uList;
                                                }
                                            }
                                            callback1(err, null);
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        callback1()
                                    }
                                });
                            });
                        }, function (err) {
                            if (err) {
                                callback(err, null);
                            } else {
                                page = Number(page);
                                var replies = result.replies.slice(page * listPageSize, (page + 1) * listPageSize);
                                var temp = {
                                    replyCount: result.replies.length,
                                    replyCountStr: toolUtil.transformNumber(result.replies.length),
                                    replies: replies
                                };
                                callback(null, temp);
                            }
                        });
                    }
                });
        }
    });
};


/**
 * 回复点赞
 */
exports.praiseReplyService = function (replyId, replyBy, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReplyPraise.findOne({
                'reply': replyId,
                'user': user._id
            }, '', function (err, result) {
                if (err) {
                    callback(err, result);
                } else {
                    if (result == null) {

                        var temp = new QuestionReplyPraise();
                        temp.reply = replyId;
                        temp.user = user._id;
                        temp.replyBy = replyBy;
                        temp.save(function () {
                            Question.findOne({'replies._id': replyId}, function (err, result) {
                                redisClient.del('question:reply:list:' + result._id);
                                callback();
                            });
                        });
                    } else {
                        var msg = {
                            "message": "无法重复点赞"
                        };
                        callback(msg, null);
                    }
                }
            })
        }
    });
};

/**
 * 获取我所提的问题和投票列表
 */
exports.getMyQuestionAndPollListService = function (page, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var index = Number(page) * listPageSize;
            var userId = user._id;

            Question.find({
                'createdBy': userId,
                community: user.community._id,
                'isValid': true
            }, '_id desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category tag images replies dateCreated createdBy')
                .skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        results.forEach(function (question) {
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;
                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                });
                            }
                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }

                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                        });
                        callback(null, results);
                    }
                })

        }
    })
};

/**
 * 获取我的问题列表（新）
 * @param page
 * @param token
 * @param callback
 */
exports.getMyQuestionListService = function (page, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        var index = Number(page) * listPageSize;
        var data = [];

        ugcIndex.find({community: user.community._id, createdBy: user._id}).skip(index).limit(listPageSize).sort({
            dateCreated: -1
        }).exec(function (err, result) {
            if (result != null) {
                async.eachSeries(result, function (ugc, callbackInner) {
                    if (ugc.category == 'neighbourActivity') {
                        neighbourActivity.findOne({_id: ugc.ugcId}, '_id title replies.replyStatus replies.images replies._id replies.replyDesc  replies.dateReplied replies.repliedBy desc category dateCreated createdBy')
                            .populate('tag', 'category value _id')
                            .populate('replies.repliedBy', '_id nickName images')
                            .populate('createdBy', '_id nickName images')
                            .exec(function (err, activity) {
                                if (activity != null) {

                                    if (activity.replies != null) {
                                        activity._doc['numberOfReplies'] = activity.replies.length;
                                        activity.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                activity._doc['adoptedReply'] = reply;
                                            }
                                        });
                                    }

                                    activity._doc.replies = undefined;

                                    if (activity._doc.adoptedReply != null && activity._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: activity._doc.adoptedReply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (temp, i) {
                                                    activity._doc.adoptedReply.replyDesc = activity._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                });
                                            }
                                            data.push(activity);
                                            callbackInner()
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        data.push(activity);
                                        callbackInner(err);
                                    }
                                } else {
                                    callbackInner(err);
                                }
                            })
                    } else {
                        Question.findOne({
                            _id: ugc.ugcId,
                            'isValid': true
                        }, '_id desc replies.replyStatus replies._id replies.replyDesc replies.images replies.dateReplied replies.repliedBy category replies dateCreated createdBy')
                            .populate('replies.repliedBy', '_id nickName images')
                            .populate('createdBy', '_id nickName images').exec(function (err, question) {
                                if (question != null) {
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;
                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                            }
                                        });
                                    }

                                    question._doc.replies = undefined;

                                    if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (temp, i) {
                                                    question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                });
                                            }
                                            data.push(question);
                                            callbackInner()
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        data.push(question);
                                        callbackInner(err);
                                    }
                                } else {
                                    callbackInner();
                                }
                            })
                    }
                }, function (err) {
                    callback(err, data);
                })
            } else {
                callback(null, []);
            }
        });
    })
};

exports.getMyReplyListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var index = Number(page) * listPageSize;
            var data = [];

            ugcReply.find({
                community: user.community._id,
                repliedBy: user._id
            }).skip(index).limit(listPageSize)
                .sort('-dateCreated')
                .exec(function (err, result) {
                    if (result != null) {
                        async.eachSeries(result, function (ugc, callbackInner) {
                            if (ugc.category == 'neighbourActivity') {
                                neighbourActivity.findOne({_id: ugc.ugcId}, '_id title replies.replyStatus replies._id replies.images replies.replyDesc replies.dateReplied replies.repliedBy desc category dateCreated createdBy images')
                                    .populate('tag', 'category value _id')
                                    .populate('replies.repliedBy', '_id nickName images')
                                    .populate('createdBy', '_id nickName images')
                                    .exec(function (err, activity) {
                                        if (activity != null) {

                                            if (activity.replies != null) {
                                                activity._doc['numberOfReplies'] = activity.replies.length;
                                                activity.replies.forEach(function (reply) {
                                                    if (reply._id + '' == ugc.replyId) {
                                                        activity._doc['myReply'] = reply;
                                                    }
                                                });
                                            }
                                            activity._doc.replies = undefined;

                                            if (activity._doc.myReply != null && activity._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                replyAt.findOne({replyId: activity._doc.myReply._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            activity._doc.myReply.replyDesc = activity._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    data.push(activity);
                                                    callbackInner()
                                                }).populate('uList', '_id nickName');
                                            } else {
                                                data.push(activity);
                                                callbackInner(err);
                                            }
                                        } else {
                                            callbackInner(err);
                                        }
                                    })
                            } else {
                                Question.findOne({
                                    _id: ugc.ugcId,
                                    'isValid': true
                                }, '_id desc replies.replyStatus replies._id replies.replyDesc replies.images replies.dateReplied replies.repliedBy category replies dateCreated createdBy images')
                                    .populate('replies.repliedBy', '_id nickName images')
                                    .populate('createdBy', '_id nickName images').exec(function (err, question) {
                                        if (question != null) {
                                            if (question.replies != null) {
                                                question._doc['numberOfReplies'] = question.replies.length;
                                                question.replies.forEach(function (reply) {
                                                    if (reply._id + '' == ugc.replyId) {
                                                        question._doc['myReply'] = reply;
                                                    }
                                                });
                                            }
                                            question._doc.replies = undefined;

                                            if (question._doc.myReply != null && question._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                replyAt.findOne({replyId: question._doc.myReply._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            question._doc.myReply.replyDesc = question._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    data.push(question);
                                                    callbackInner()
                                                }).populate('uList', '_id nickName');
                                            } else {
                                                data.push(question);
                                                callbackInner(err);
                                            }
                                        } else {
                                            callbackInner();
                                        }
                                    })
                            }
                        }, function (err) {
                            callback(err, data);
                        })
                    } else {
                        callback(null, []);
                    }
                });
        }
    })
};

/**
 * 获取我参与回答的问题列表
 */
exports.getMyRepliedQuestionListService = function (page, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var index = Number(page) * listPageSize;
            var userId = user._id;

            Question.find({
                'createdBy': {'$ne': userId},
                'replies.repliedBy': userId,
                community: user.community._id,
                'isValid': true
            }, '_id desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category tag images replies dateCreated createdBy')
                .skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        results.forEach(function (question) {
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;

                                if (userId != question.createdBy._id) {
                                    question.replies.forEach(function (reply) {
                                        if (userId == reply.repliedBy._id) {
                                            question._doc['myReply'] = reply;
                                        }
                                    });
                                }
                            }
                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }

                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                        });
                        callback(null, results);
                    }
                })
        }
    })
};

/**
 * 问题置顶
 */
exports.moveQuestionToTopService = function (opt, callback) {

    var Num = 0;

    async.series([
        function (callbackInner) {
            if (opt.category != null) {
                Question.find({
                    community: opt.communityId,
                    isValid: true,
                    category: opt.category
                }).sort({categoryOrder: -1}).limit(3)
                    .exec(function (err, results) {
                        Num = (results[0].categoryOrder ? results[0].categoryOrder : 0) + 1;
                        if (results.length == 3 && results[2].categoryOrder > 0) {
                            results[2].categoryOrder = undefined;
                            results[2].save(callbackInner);
                        } else {
                            callbackInner(null, null);
                        }
                    });
            } else {
                Question.find({
                    community: opt.communityId,
                    isValid: true
                }).sort({allOrder: -1}).limit(3)
                    .exec(function (err, results) {
                        Num = (results[0].allOrder ? results[0].allOrder : 0) + 1;
                        if (results.length == 3 && results[2].allOrder > 0) {
                            results[2].allOrder = undefined;
                            results[2].save(callbackInner);
                        } else {
                            callbackInner(null, null);
                        }
                    });
            }
        },
        function (callbackInner) {
            if (opt.category != null) {
                Question.update({_id: opt.questionId}, {categoryOrder: Num}).exec(callbackInner);
            } else {
                Question.update({_id: opt.questionId}, {allOrder: Num}).exec(callbackInner);
            }
        }
    ], callback)
};

/**
 * 取消置顶
 */
exports.cancelTopQuestionService = function (input, callback) {
    if (input.category != null) {
        Question.findOne({_id: input.questionId}, function (err, result) {
            result.categoryOrder = undefined;
            result.save(callback);
        })
    } else {
        Question.findOne({_id: input.questionId}, function (err, result) {
            result.allOrder = undefined;
            result.save(callback);
        })
    }
};

/**
 * 回复置顶
 */
exports.moveReplyToTopService = function (questionId, replyId, callback) {
    async.waterfall([
        function (callbackInner) {
            Question.findOne({_id: questionId, 'isValid': true}).exec(function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == null) {
                var msg = {
                    "message": 'No such question'
                };
                callbackInner(msg, null);
            } else {
                var replies = result.replies;
                replies.sort(function (a, b) {
                    return a.displayOrder > b.displayOrder ? -1 : 1;
                });
                var maxValue;

                if (replies[0]._doc.displayOrder == undefined) {
                    maxValue = 1;
                } else {
                    maxValue = replies[0]._doc.displayOrder + 1;
                }
                Question.update({
                    _id: questionId,
                    'replies._id': replyId
                }, {'replies.$.displayOrder': maxValue}).exec(callbackInner);
            }
        }
    ], callback)
};

/**
 * 获取推荐给我的问题和投票列表
 */
exports.getRecommendedQuestionAndPollListService = function (token, page, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {

            //restClient.get('http://localhost:8003?userid=' + user._id, function (data, response) {
            //    var ids = data.ids;
            //
            //    Question.find({_id: {$in: ids}})
            //}).on('error', function (err) {
            //
            //});

            Question.find({
                'community': user.community._id,
                recommend: true,
                'isValid': true
            }, '_id desc displayOrder browserCount community category status tag images replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy pollOptions pollUserList dateCreated createdBy')
                .populate('tag', 'category value _id').populate('replies.repliedBy', '_id nickName images')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {

                            //计算问题回复数量
                            var replyCount = 0;

                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;
                                replyCount = question.replies.length;
                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                })
                            }

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
//=================================================================================
//                            if (question.browserCount >= 200) {
//                                question._doc['hot'] = true;
//                            } else {
//                                question._doc['hot'] = false;
//                            }
//
//                            var ranking;
//                            var diffDay = moment().diff(moment(question.dateCreated), 'days')
//                            if (diffDay == 0) {
//                                ranking = 0.1 * 0.5
//                            } else if (diffDay > 0 && diffDay < 7) {
//                                ranking = 0.1 * 0.3
//                            } else {
//                                ranking = 0.1 * 0.2
//                            }
//
//                            ranking += 0.1 * (replyCount > 10) ? 0.8 : 0.2;
//
//                            if (question.browserCount > 100) {
//                                ranking += 0.2 * 0.6
//                            } else if (question.browserCount > 10 && question.browserCount <= 100) {
//                                ranking += 0.2 * 0.3
//                            } else {
//                                ranking += 0.2 * 0.1
//                            }
//
//                            if (question._doc.adoptedReply == null) {
//                                ranking += 0.15
//                            }
//
//
//                            if (question._doc.tag != null) {
//                                Users.findOne({_id: user._id}, 'hobbies', function (err, result) {
//                                    if (result.hobbies.indexOf(question._doc.tag) > -1) {
//                                        ranking += 0.3
//                                    }
//                                })
//                            }
//                            question._doc['ranking'] = ranking;
//                            results.sort(function (a, b) {
//                                return b._doc.ranking - a._doc.ranking
//                            });
//
//                            results.forEach(function (result) {
//                                result._doc.ranking = undefined;
//                            });
//                            results = results.splice(0, 20);

                            //过滤tag为null的问题
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                            question._doc.pollUserList = undefined;

                        });

                        results.sort(function (a, b) {
                            if (a.displayOrder == undefined) {
                                a.displayOrder = 0;
                            }
                            if (b.displayOrder == undefined) {
                                b.displayOrder = 0;
                            }
                            if (a.displayOrder > b.displayOrder) {
                                return -1
                            } else if (a.displayOrder < b.displayOrder) {
                                return 1
                            } else {
                                return b.dateCreated - a.dateCreated
                            }
                        });

                        var data = results.slice(page * listPageSize, (page + 1) * listPageSize);

                        callback(null, data);
                    }
                })
        }
    })
};

/**
 * 获取有采纳回答的问题
 * @param communityId
 * @param callback
 */
exports.getQuestionByAdoptedReplyService = function (communityId, callback) {
    Question.find({
        'community': communityId,
        'replies.replyStatus': '已采纳',
        'isValid': true
    }, '_id desc displayOrder browserCount community category tag images replies.replyStatus replies._id replies.replyDesc replies.dateReplied replies.repliedBy dateCreated createdBy')
        .populate('tag', 'category value _id').populate('replies.repliedBy', '_id nickName images')
        .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-dateCreated').limit(20).exec(function (err, results) {
            if (results == undefined || results == null) {
                var msg = {
                    "message": 'get err'
                };
                callback(msg, null);
            } else {
                results.forEach(function (question) {
                    if (question.replies != null) {
                        question._doc['numberOfReplies'] = question.replies.length;
                        question.replies.forEach(function (reply) {
                            if (reply.replyStatus == '已采纳') {
                                question._doc['adoptedReply'] = reply;
                            }
                        })
                    }
                    question.replies = undefined;
                    if (question.browserCount == null) {
                        question.browserCount = 0;
                    }
                    if (question._doc.tag == null || question._doc.tag.length == 0) {
                        question._doc.tag = undefined;
                    }
                });
                callback(null, results);
            }
        });
};

/**
 * 获取小区所有问题列表
 */
exports.getAllCommunityQuestionListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;
            var date = new Date();

            Question.find({
                'community': communityId,
                'isValid': true
            }, '_id desc allOrder community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy').skip(index).limit(listPageSize)
                .populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit').sort({
                    allOrder: -1,
                    dateLastModified: -1
                }).exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {
                            //计算问题回复数量
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;

                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                })
                            }
                            question._doc.replies = undefined;
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }

                            //置顶标识
                            question._doc['isTop'] = question._doc.allOrder ? true : false;
                            question._doc.allOrder = undefined;

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }

                            if (question.dateLastModified > date) {
                                question.dateLastModified = question.dateCreated;
                            }

                            question._doc['categoryName'] = questionCategory[question.category];

                            if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                                question.createdBy.roomUnit = undefined;
                            }
                            question.createdBy.showUnit = undefined;
                        });
                        callback(null, results);
                    }
                })
        }
    });
};

/**
 * 获取互助全部列表
 * @param ts   时间戳
 * @param token
 * @param sortName 排序
 * @param level 帖子级别
 * @param range 范围
 * @param vCode
 * @param callback
 */
exports.getAllCommunityQuestionListNewService = function (ts, token, sortName, level, range, vCode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var date = ts == '0' ? new Date() : new Date(Number(ts));
            sortName = sortName == 'dateCreated' ? sortName : 'lastReply';

            //查询条件
            var opt = {
                //category: {$ne: 'advertisement'}  //去广告
            };

            if (ts != '0') opt.displayOrder = null;
            //if (level != null) {        //精华帖
            //    opt.level = 1;
            //}

            opt[sortName] = {$lt: date};    //时间条件

            if (range == 'around') {    //周边小区
                if (level == null) {
                    opt['$or'] = [{community: user.community._id}, {aroundCommunity: user.community._id}]
                } else {
                    opt['$and'] = [{$or: [{community: user.community._id}, {aroundCommunity: user.community._id}]}
                        , {$or: [{level: 1}, {category: {$in: ['question', 'secondhand', 'free', 'lostAndFound']}}]}]
                }
            } else {                    //本小区
                opt.community = user.community._id;
                if (level != null) {
                    opt['$or'] = [{level: 1}, {category: {$in: ['question', 'secondhand', 'free', 'lostAndFound']}}]
                }
            }

            var sort = {
                displayOrder: -1
            };
            sort[sortName] = -1;

            ugcIndex.find(opt).limit(listPageSize).sort(sort).exec(function (err, result) {
                if (result != null) {
                    questionService.getQuestionListByUgcIndex(user, result, vCode, function (err, result) {
                        var data = {
                            list: result,
                            community: opt.community
                        };
                        callback(err, data);
                    })
                } else {
                    callback(err, {list: [], community: opt.community});
                }
            });
        }
    })
};

/**
 * 根据标签获取列表
 * @param ts
 * @param tagId
 * @param token
 * @param vCode
 * @param callback
 */
exports.getQuestionListByTagService = function (ts, tagId, token, vCode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var date = ts == '0' ? new Date() : new Date(Number(ts));

            ugcIndex.find({
                community: user.community._id,
                tag: tagId,
                lastReply: {$lt: date}
            }, '-displayOrder').limit(listPageSize).sort({
                lastReply: -1
            }).exec(function (err, result) {
                if (result != null) {
                    questionService.getQuestionListByUgcIndex(user, result, vCode, callback)
                } else {
                    callback(null, []);
                }
            });
        }
    })
};

/**
 * 根据索引获取问题或者其他
 * @param user
 * @param result
 * @param vCode
 * @param callback
 */
exports.getQuestionListByUgcIndex = function (user, result, vCode, callback) {
    var data = [];
    async.eachSeries(result, function (ugc, callbackInner) {
        if (ugc.category == 'neighbourActivity') {
            neighbourActivity.findOne({_id: ugc.ugcId}, '_id title deadline partakeNum desc category tag images.imageURL images._id dateCreated createdBy partake replies browserCount status activityType praiseCount community')
                .populate('tag', 'category value _id').populate('community', 'communityName')
                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit userRole')
                .populate('partake.user', '_id nickName images userType authenticationStatus')
                .exec(function (err, activity) {
                    if (activity != null && activity.createdBy != null) {

                        if (activity.replies != null) {
                            activity._doc['numberOfReplies'] = activity.replies.length;
                            activity._doc['replyCountStr'] = toolUtil.transformNumber(activity.replies.length);
                        }
                        activity._doc['browserCountStr'] = toolUtil.transformNumber(activity._doc.browserCount);
                        activity._doc.replies = undefined;
                        var number = 0;
                        var uList = [];

                        activity.partake.forEach(function (par) {
                            number += par.number;
                            if (par.partakeType == 2) {
                                par._doc.user = {
                                    nickName: par.name,
                                    images: [{imageURL: wechatImage}]
                                }
                            }

                            if (par._doc.user != null && uList.length < 9) {
                                uList.push(par.user)
                            }
                        });

                        activity._doc.partakeNum = activity.partake.length + '';
                        activity._doc.uList = uList;
                        activity._doc['number'] = number;
                        activity._doc['dateLastModified'] = ugc.lastReply;
                        activity._doc['activityStatus'] = activity.status;

                        var isOtherCommunity = user.community._id != activity.community._id + '';

                        if (activity.createdBy.roomUnit != null && activity.createdBy.roomUnit != '')
                            activity.createdBy._doc.roomUnit = Number(vCode) >= 106000 && !isNaN(activity.createdBy.roomUnit) ? activity.createdBy.roomUnit + '单元' : activity.createdBy.roomUnit;

                        if ((activity.createdBy.showUnit != null && !activity.createdBy.showUnit) || isOtherCommunity) {
                            activity.createdBy.roomUnit = undefined;
                        }
                        activity.createdBy.showUnit = undefined;

                        activity._doc['isTop'] = ugc.displayOrder ? true : false;
                        activity._doc.partake = undefined;

                        activity._doc.praiseCount = toolUtil.transformNumber(activity.praiseCount);

                        questionPraise.findOne({activity: activity._id, user: user._id}, function (err, result) {
                            activity._doc['isPraise'] = result != null;
                            data.push(activity);
                            callbackInner()
                        });
                    } else {
                        callbackInner();
                    }
                })
        } else {
            Question.findOne({_id: ugc.ugcId}, '_id desc browserCount replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy category tag images replies dateCreated createdBy praiseCount community')
                .populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus userRole')
                .populate('community', '_id communityName')
                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit userRole')
                .exec(function (err, question) {
                    if (question != null && question.createdBy != null) {
                        //计算问题回复数量
                        if (question.replies != null) {
                            question._doc['numberOfReplies'] = question.replies.length;
                            question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                            question.replies.forEach(function (reply) {
                                if (reply.replyStatus == '已采纳') {
                                    question._doc['adoptedReply'] = reply;
                                }
                            })
                        }

                        question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                        question._doc.replies = undefined;

                        var isOtherCommunity = user.community._id != question.community._id + '';

                        if (question.createdBy.roomUnit != null && question.createdBy.roomUnit != '')
                            question.createdBy._doc.roomUnit = Number(vCode) >= 106000 && !isNaN(question.createdBy.roomUnit) ? question.createdBy.roomUnit + '单元' : question.createdBy.roomUnit;

                        if ((question.createdBy.showUnit != null && !question.createdBy.showUnit) || isOtherCommunity) {
                            question.createdBy.roomUnit = undefined;
                        }
                        question.createdBy.showUnit = undefined;
                        question._doc['isTop'] = ugc.displayOrder ? true : false;

                        question._doc['dateLastModified'] = ugc.lastReply;

                        question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);

                        questionPraise.findOne({question: question._id, user: user._id}, function (err, result) {
                            question._doc['isPraise'] = result != null;

                            if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                    if (at != null && at.uList != null) {
                                        at.uList.forEach(function (temp, i) {
                                            question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                        });
                                    }

                                    data.push(question);
                                    callbackInner()
                                }).populate('uList', '_id nickName');
                            } else {
                                data.push(question);
                                callbackInner(err);
                            }
                        });
                    } else {
                        callbackInner(err);
                    }
                })
        }
    }, function (err) {
        callback(err, data);
    })
};


/**
 * 获取小区所有投票
 */
exports.getAllCommunityPollListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;

            Question.find({
                'category': 'poll',
                'community': user.community._id,
                'isValid': true
            }, '_id desc displayOrder community category tag status images pollOptions dateCreated pollUserList createdBy').skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-displayOrder').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {

                            //如果是投票，判断用户是否已投过票，voted字段表示
                            var pollList = question.pollUserList;
                            if (pollList != null && pollList.indexOf(user._id) != -1) {
                                question._doc['voted'] = 'Yes'
                            } else {
                                question._doc['voted'] = 'No'
                            }
                            if (pollList != null) {
                                question._doc['numberOfReplies'] = pollList.length;
                            }
                            question._doc.pollUserList = undefined;

                            //过滤tag为null的问题
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }

                        });
                        callback(null, results);
                    }
                })
        }
    })
};

/**
 * 获取小区专题列表
 */
exports.getAllCommunitySpecialTopicListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;

            Question.find({
                'category': 'specialTopic',
                'community': communityId,
                'isValid': true
            }, '_id title desc community browserCount replies category images dateCreated').skip(index).limit(listPageSize)
                .populate('community', '_id communityName').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {
                            question._doc['numberOfReplies'] = question.replies.length;
                            question._doc.replies = undefined;

                            question._doc.pollUserList = undefined;
                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
                        });
                        callback(null, results);
                    }
                })
        }
    });
};


/**
 * 根据分类获取问题和投票列表
 */
exports.getCategorizedQuestionAndPollListService = function (page, tagId, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;
            var date = new Date();

            Dic.findOne({_id: tagId}, 'value', function (err, tagName) {
                if (tagName.value == '推荐') {
                    questionService.getRecommendedQuestionAndPollListService(token, Number(page), callback);
                } else {
                    Question.find({
                        'tag': tagId,
                        'community': communityId,
                        'isValid': true
                    }, '_id desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy').skip(index).limit(listPageSize)
                        .populate('tag', 'category value _id')
                        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                        .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus').sort('-dateCreated').exec(function (err, results) {
                            if (results == undefined || results == null) {
                                var msg = {
                                    "message": 'get err'
                                };
                                callback(msg, null);
                            } else {
                                results.forEach(function (question) {
                                    //计算问题回复数量
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;
                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                            }
                                        })
                                    }
                                    question._doc.replies = undefined;
                                    if (question._doc.tag == null || question._doc.tag.length == 0) {
                                        question._doc.tag = undefined;
                                    }
                                    question._doc.pollUserList = undefined;

                                    if (question.browserCount == null) {
                                        question.browserCount = 0;
                                    }

                                    if (question.dateLastModified > date) {
                                        question.dateLastModified = question.dateCreated;
                                    }
                                });
                                callback(null, results);
                            }
                        })
                }
            })
        }
    });
};
/**
 * 搜索问题和投票列表
 */
exports.searchQuestionAndPollListService = function (keyword, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {

            var searchArray = [];

            var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]");
            var rs = "";
            for (var i = 0; i < keyword.length; i++) {
                rs = rs + keyword.substr(i, 1).replace(pattern, '');
            }

            var temp = encodeURIComponent(rs);

            if (temp == null || temp == '') {
                var res = [];
                callback(null, res);
            } else {
                console.log('temp ==' + temp);
                restClient.get('http://' + SolrHost + '/core0/select?q=%7B!edismax+mm%3D"1<50%25+4<-45%25"%7Ddesc%3A' + temp + '&fq=community%3A' + user.community._id + '&rows=20&wt=json&indent=true&hl=true&hl.fl=desc&hl.simple.pre=<font+color%3D%27%23' + hlColor + '%27>&hl.simple.post=<%2Ffont>', function (data, response) {
                    if (response.statusCode == 200) {
                        var v = false;
                        if (typeof data == 'string') {
                            try {
                                data = JSON.parse(data);
                            } catch (e) {

                            }
                        }
                        if (typeof data == "object" && data.response != null) {
                            var docs = data.response.docs;
                            var ids = new Array(docs.length);

                            for (var i = 0; i < docs.length; i++) {
                                ids[i] = docs[i]._id;
                            }

                            var questions = [];

                            async.eachSeries(ids, function (id, callbackInner) {
                                Question.findOne({
                                    _id: id, 'community': user.community._id,
                                    'isValid': true
                                }, '_id desc community browserCount category status tag images replies pollOptions dateCreated createdBy').populate('tag', 'category value _id')
                                    .populate('community', '_id communityName').populate('createdBy', '_id nickName').exec(function (err, result) {
                                        if (result != null) {
                                            questions.push(result);
                                        }
                                        callbackInner();
                                    });
                            }, function (err) {
                                questions.forEach(function (question) {
                                    question._doc.desc = data.highlighting[question._id].desc[0];

                                    //计算问题回复数量
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;

                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                            }
                                        })
                                    }
                                    question._doc.replies = undefined;
                                    if (question._doc.tag == null || question._doc.tag.length == 0) {
                                        question._doc.tag = undefined;
                                    }
                                    if (question.browserCount == null) {
                                        question.browserCount = 0;
                                    }
                                    if (question.browserCount >= 200) {
                                        question._doc['hot'] = true;
                                    } else {
                                        question._doc['hot'] = false;
                                    }
                                });
                                callback(null, questions);
                            });
                        } else {
                            logger.error(data);
                            callback(null, searchArray);
                        }
                    } else {
                        callback(null, searchArray);
                    }
                }).on('error', function (err) {
                    logger.error('search went wrong on the request' + err.message);
                    callback(null, searchArray);
                });
            }
        }
    });
};

/**
 * 获取专家解答问题
 */
exports.getExpertRepliedQuestionListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {

            var index = Number(page) * listPageSize;
            //假数据
            Question.find({
                'community': user.community._id,
                'isValid': true,
                'replies': {'$not': {'$size': 0}},
                'replies.replyType': {'$ne': null}
            }, 'desc createdBy browserCount replies.replyDesc replies.dateReplied replies.repliedBy replies.replyType').skip(index).limit(listPageSize).populate('createdBy', '_id nickName images').populate('replies.repliedBy', '_id nickName images')
                .exec(function (err, results) {
                    if (results != null) {
                        results.forEach(function (result) {

                            //去掉非专家回复，显示最新专家回复
                            var replies = result.replies;
                            if (replies != null && replies.length != 0) {

                                replies.sort(function (a, b) {
                                    return b.dateReplied - a.dateReplied;
                                });

                                for (var i = 0; i < replies.length; i++) {
                                    if (replies[i].replyType != null) {
                                        replies.splice(0, i);
                                        break;
                                    }
                                }
                                result.replies = [replies[0]];
                            }

                            if (result.browserCount == null) {
                                result.browserCount = 0;
                            }
                            if (result.browserCount >= 200) {
                                result._doc['hot'] = true;
                            } else {
                                result._doc['hot'] = false;
                            }
                        });
                        callback(null, results);
                    } else {
                        callback(null, null);
                    }
                });
        }
    });
};

/**
 * 最新问题和投票
 */
exports.getLatestQuestionListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;

            Question.find({
                'community': user.community._id,
                'isValid': true
            }, '_id desc displayOrder browserCount community category status tag images replies pollOptions pollUserList dateCreated createdBy').skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-displayOrder').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {

                            //如果是投票，判断用户是否已投过票，voted字段表示
                            if (question.category == 'poll') {
                                var pollList = question.pollUserList;
                                if (pollList != null && pollList.indexOf(user._id) != -1) {
                                    question._doc['voted'] = 'Yes'
                                } else {
                                    question._doc['voted'] = 'No'
                                }
                                if (pollList != null) {
                                    question._doc['numberOfReplies'] = pollList.length;
                                }
                            } else {
                                //计算问题回复数量
                                if (question.replies != null) {
                                    question._doc['numberOfReplies'] = question.replies.length;

                                    question.replies.forEach(function (reply) {
                                        if (reply.replyStatus == '已采纳') {
                                            question._doc['adoptedReply'] = reply;
                                        }
                                    })
                                }
                            }
                            //过滤tag为null的问题
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                            question._doc.pollUserList = undefined;

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
                            if (question.browserCount >= 200) {
                                question._doc['hot'] = true;
                            } else {
                                question._doc['hot'] = false;
                            }

                        });
                        callback(null, results);
                    }
                })
        }
    })
};


/**
 * 获取达人排行榜
 */
exports.getTalentListService = function (tagId, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var data = [];
            Users.findOne({nickName: '小6客服'}, '_id', function (err, result) {
                QuestionReplyStatistics.find({
                    'tag': tagId,
                    'community': user.community._id,
                    'user': {$ne: result._id}
                }, 'user replyCount adoptedCount').populate('user', '_id nickName images userType authenticationStatus community').exec(function (err, results) {
                    if (results != null) {

                        results.forEach(function (qu) {
                            if (qu.user != null && qu.user.community != null && qu.user.community == user.community._id) {
                                data.push(qu);
                            }
                        });

                        data.sort(function (a, b) {
                            if (a.user.userType != 'talent' && b.user.userType == 'talent') {
                                return 1
                            } else if (a.user.userType == 'talent' && b.user.userType != 'talent') {
                                return -1
                            } else if (a.user.authenticationStatus && !b.user.authenticationStatus) {
                                return -1
                            } else if (!a.user.authenticationStatus && b.user.authenticationStatus) {
                                return 1
                            } else {
                                return (b.replyCount + b.adoptedCount) - (a.replyCount + a.adoptedCount);
                            }

                        });
                    }
                    callback(err, data);
                })
            });

        }
    });
};


//==============================新版求助==================================


exports.getCategoryQuestionListService = function (token, category, page, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;

            var date = new Date();

            Question.find({
                'category': category,
                'community': communityId,
                'isValid': true
            }, '_id desc categoryOrder community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy').skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit').sort({
                    categoryOrder: -1,
                    dateLastModified: -1
                }).exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var data = [];
                        callback(null, data);
                    } else {
                        results.forEach(function (question) {
                            //计算问题回复数量
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;

                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                })
                            }
                            question._doc.replies = undefined;
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
                            //置顶标识
                            question._doc['isTop'] = question._doc.categoryOrder ? true : false;
                            question._doc.categoryOrder = undefined;

                            if (question.dateLastModified > date) {
                                question.dateLastModified = question.dateCreated;
                            }

                            if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                                question.createdBy.roomUnit = undefined;
                            }
                            question.createdBy.showUnit = undefined;
                        });
                        callback(null, results);
                    }
                })
        }
    });
};

exports.getCategoryQuestionListNewService = function (token, category, ts, sortName, vCode, range, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;

            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var opt = {
                category: category,
                isValid: true
            };

            opt[sortName] = {$lt: date};
            var sort = {};

            if (ts != '0') {
                opt.categoryOrder = null;
            } else {
                sort.categoryOrder = -1;
            }

            if (range == 'around') {    //周边小区
                opt['$or'] = [{community: user.community._id}, {aroundCommunity: user.community._id}]
            } else {                    //本小区
                opt.community = user.community._id;
            }


            sort[sortName] = -1;

            var data = [];

            Question.find(opt, 'praiseCount _id desc categoryOrder community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy')
                .limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit userRole').sort(sort).exec(function (err, results) {
                    if (results == undefined || results == null) {
                        callback(null, data);
                    } else {

                        async.eachSeries(results, function (question, c1) {
                            if (question.createdBy != null) {
                                if (question.replies != null) {
                                    question._doc['numberOfReplies'] = question.replies.length;
                                    question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);

                                    question.replies.forEach(function (reply) {
                                        if (reply.replyStatus == '已采纳') {
                                            question._doc['adoptedReply'] = reply;
                                        }
                                    })
                                }
                                question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                                question._doc.replies = undefined;
                                if (question._doc.tag == null || question._doc.tag.length == 0) {
                                    question._doc.tag = undefined;
                                }

                                if (question.browserCount == null) {
                                    question.browserCount = 0;
                                }
                                //置顶标识
                                question._doc['isTop'] = question._doc.categoryOrder ? true : false;

                                var isOtherCommunity = user.community._id != question.community._id + '';

                                if (question.createdBy.roomUnit != null && question.createdBy.roomUnit != '')
                                    question.createdBy._doc.roomUnit = Number(vCode) >= 106000 && !isNaN(question.createdBy.roomUnit) ? question.createdBy.roomUnit + '单元' : question.createdBy.roomUnit;

                                if ((question.createdBy.showUnit != null && !question.createdBy.showUnit) || isOtherCommunity) {
                                    question.createdBy.roomUnit = undefined;
                                }
                                question.createdBy.showUnit = undefined;

                                question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);

                                questionPraise.findOne({
                                    question: question._id,
                                    user: user._id
                                }, function (err, result) {
                                    if (result == null) {
                                        question._doc['isPraise'] = false;
                                    } else {
                                        question._doc['isPraise'] = true;
                                    }

                                    if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (temp, i) {
                                                    question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                });
                                            }
                                            data.push(question);
                                            c1();
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        data.push(question);
                                        c1();
                                    }
                                });
                            } else {
                                c1();
                            }
                        }, function (err, result) {
                            callback(null, data);
                        });
                    }
                })
        }
    });
};


//=========================================== web端=============================================

/**
 * questionService.js
 * 创建问题
 * author:chenjinzhuan
 */
exports.createQuestionService = function (input, callback) {
    var temp = new Question();
    temp.category = input.category;
    temp.desc = input.desc;
    temp.status = '未解决';
    temp.createdBy = input._id;
    temp.community = input.community;

    if (data == 'unknown') {
        temp.save(function (err, question) {
            callbackInner(null, question);
        })
    } else {
        Dic.findOne({'value': data}, '', function (err, result) {
            if (result == null) {
                temp.save(function (err, question) {
                    callbackInner(null, question);
                });
            } else {
                temp.tag = result._id;
                temp.save(function (err, question) {
                    callback(null, question);
                });
            }
        })
    }


};

/**
 * questionService.js
 * 更新问题
 * author:chenjinzhuan
 */
exports.updateOneQuestionService = function (id, input, callback) {

    async.series([
        function (callbackInner) {
            Question.findOne({'_id': id}, function (err, result) {
                var replyC = 0;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }

                var tags = result.tag;

                Dic.find({'_id': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
                    if (res != null) {
                        res.forEach(function (tag) {
                            QuestionAndReplyCount.findOne({
                                'community': result.community,
                                'tag': tag._id
                            }, '', function (err, qc) {
                                if (qc == null) {
                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = 0;
                                    temp.replyCount = 0;
                                    temp.community = result.community;
                                    temp.tag = tag;
                                    temp.save();
                                } else {
                                    qc.questionCount -= 1;
                                    qc.replyCount -= replyC;
                                    qc.save();
                                }
                            })
                        })
                    }
                    callbackInner(err, null);
                })
            })
        },
        function (callbackInner) {
            var tags = input.tag;

            Question.findOne({'_id': id}, function (err, result) {
                var replyC = 0;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }

                Dic.find({'_id': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
                    res.forEach(function (tag) {
                        QuestionAndReplyCount.findOne({
                            'community': result.community,
                            'tag': tag
                        }, '', function (err, qc) {
                            if (qc == null) {
                                var temp = new QuestionAndReplyCount();
                                temp.questionCount = 1;
                                temp.replyCount = replyC;
                                temp.community = result.community;
                                temp.tag = tag;
                                temp.save();
                            } else {
                                qc.questionCount += 1;
                                qc.replyCount += replyC;
                                qc.save();
                            }
                        })
                    });
                    callbackInner(err, null);
                })
            });
        },
        function (callbackInner) {
            Question.update({_id: id},
                {
                    $set: {
                        'desc': input.desc,
                        'tag': input.tag
                    }
                }, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: id}, {$set: {'tag': input.tag}}, callbackInner);
        }
    ], callback);
};

/**
 * questionService.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getQuestionListService = function (callback) {
    Question.find({
        category: 'question',
        isValid: true
    }).populate('community', '_id communityName communityAddress')
        .populate('tag', 'value')
        .populate('createdBy', 'userName email mobilePhone nickName').sort('-dateCreated').exec(function (err, results) {
            if (err) {
                return callback(err);
            } else {
                if (results != null) {
                    results.forEach(function (question) {
                        var data = [];
                        if (question.tag != null) {
                            question.tag.forEach(function (t) {
                                data.push(t.value);
                            });
                            question._doc.tag = data
                        }
                    })
                }
                return callback(null, results);
            }
        });
};

/**
 * questionService.js
 * 根据条件问题列表
 * author:chenjinzhuan
 */
exports.searchQuestionService = function (question, callback) {
    //根据关键词查询问题
    Question.find({desc: new RegExp(question.key)}).populate('community', '_id communityName communityAddress')
        .populate('createdBy', 'userName email mobilePhone nickName').exec(function (err, results) {
            if (err) {
                return callback(err);
            } else if (results == undefined || results == null) {
                return callback('no results', null);
            } else {
                //logger.debug('results:'+ results);
                return callback(null, results);
            }
        });

    //async.waterfall([
    //    //查询小区的id
    //    function(callbackInner){
    //        Community.findOne({'communityName':question.communityName},'_id', function (err, results) {
    //            if(err){
    //                return callback(err);
    //            }else if(results == undefined || results == null){
    //                return callback('no results',null);
    //            }else{
    //                return callbackInner(null, results);
    //            }
    //        });
    //    },
    //    //根据小区id查询问题
    //    function(results){
    //        Question.find({'community':results._id}).populate('community', '_id communityName communityAddress')
    //            .populate('createdBy','userName email mobilePhone nickName').exec(function(err,results){
    //                if(err){
    //                    return callback(err);
    //                }else if(results == undefined || results == null){
    //                    return callback('no results', null);
    //                }else{
    //                    //logger.debug('results:'+ results);
    //                    return callback(null,results);
    //                }
    //            });
    //    }
    //]);

};

/**
 * questionService.js
 * 通过Id获取问题
 * author:chenjinzhuan
 */
exports.getQuestionByIdService = function (id, callback) {

    Question.findOne({_id: id}).populate('community', '_id communityName communityAddress').populate('tag', 'value')
        .populate('createdBy', 'userName email mobilePhone nickName').exec(function (err, results) {
            if (err) {
                return callback(err);
            } else if (results == undefined || results == null) {
                return callback('no results', null);
            } else {

                for (var i = 0; i < results["images"].length; i++) {
                    results["images"][i] = fastDfsHostIp + results["images"][i]["imageURL"];
                }
                logger.debug(results["images"]);

                return callback(null, results);
            }
        });
};

/**
 * questionService.js
 * 删除问题
 * author:chenjinzhuan
 */
exports.deleteOneQuestionService = function (id, callback) {
    Question.findOneAndRemove({_id: id}, callback);
};

/**
 * questionService.js
 * 修改问题顺序
 * author:chenjinzhuan
 */
exports.changeQuestionOrderService = function (question, callback) {
    if (question.order >= 1 && question.order <= 5) {
        var displayOrder = 6 - question.order;
    } else {
        return callback('wrong order');
    }

    //1.查找问题所属小区的所有问题
    async.waterfall([
        function (callbackInner) {
            Question.find({community: question.community._id}, function (err, results) {
                if (err) {
                    return callback(err);
                } else if (results == undefined || results == null) {
                    return callback('no results', null);
                } else {
                    //logger.debug('results:'+ results);
                    return callbackInner(null, results);
                }
            });
        },
        //2.判断所有问题中是否存在给定的顺序，如果存在，则将问题的displayorder置空
        function (results, callbackInner) {
            for (var i = 0; i < results.length; ++i) {
                if (results[i].displayOrder == displayOrder) {
                    Question.update({_id: results[i]._id}, {$set: {displayOrder: null}}, function (err, results) {
                        if (err) {
                            return callbackInner(err);
                        } else if (results == undefined || results == null) {
                            return callbackInner('no results');
                        } else {
                            //logger.debug('results:'+ results);
                            return callbackInner(null);
                        }
                    });
                    //return callbackInner(null);
                }
            }
            //如果不存在已有的displayOrder，则直接返回
            return callbackInner(null);
        },
        //3.设置displayOrder
        function (callbackInner) {
            Question.findOneAndUpdate({'_id': question._id}, {'displayOrder': displayOrder}, function (err, results) {
                if (err) {
                    return callbackInner(err);
                } else if (results == undefined || results == null) {
                    return callbackInner('no results', null);
                } else {
                    //logger.debug('results:'+ results);
                    return callback(null, results);
                }
            });
        }
    ], callback);
};

/**
 * questionService.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getReplyListService = function (questionId, callback) {
    Question.find({_id: questionId}).populate('community', '_id communityName communityAddress')
        .populate('createdBy', 'userName email mobilePhone nickName')
        .populate('replies.repliedBy', 'userName email mobilePhone nickName')
        .exec(function (err, results) {
            if (err) {
                return callback(err);
            } else if (results == undefined || results == null || results.length == 0) {
                return callback('no results', null);
            } else {
                return callback(null, results[0]);
            }
        });
};

/**
 * questionService.js
 * 根据条件问题列表
 * author:chenjinzhuan
 */
exports.searchReplyService = function (input, callback) {
    async.waterfall([
            //根据问题Id查询所有回复
            function (callbackInner) {
                //根据关键词查询问题
                Question.find({'_id': input.questionId}).populate('community', '_id communityName communityAddress')
                    .populate('createdBy', 'userName email mobilePhone nickName')
                    .populate('replies.repliedBy', 'userName email mobilePhone nickName')
                    .exec(function (err, results) {
                        if (err) {
                            return callback(err);
                        } else if (results == undefined || results == null || results.length == 0) {
                            return callback('no results', null);
                        } else {
                            //logger.debug('results:'+ results);
                            return callbackInner(null, results[0].replies);
                        }
                    });
            },
            //查找回复数组中匹配的回复放入另一个数组中返回
            function (replies) {
                var reg = new RegExp(input.key);
                var results = [];
                for (var i = 0; i < replies.length; ++i) {
                    if (replies[i].replyDesc.match(reg)) {
                        results.push(replies[i]);
                    }
                }
                return callback(null, results);
            }
        ]
    );
};

exports.getNoReplyQuestionListService = function (communityId, callback) {

    var time = new Date(new Date().getTime() - 10 * 60 * 1000);

    //var opt = {
    //    replies: {$size: 0},
    //    isValid: true,
    //    dateCreated: {$lt: time}
    //};
    //
    //if (communityId != 1) {
    //    opt.community = communityId;
    //}

    if (communityId == '1') {
        Question.find({
            replies: {$size: 0},
            isValid: true,
            dateCreated: {$lt: time}
        }, '_id desc createdBy community dateCreated').populate('community', '_id communityName').populate('createdBy', '_id nickName').sort('dateCreated').exec(callback)
    } else {
        Question.find({
            replies: {$size: 0},
            community: communityId,
            isValid: true,
            dateCreated: {$lt: time}
        }, '_id desc createdBy community dateCreated').populate('community', '_id communityName').populate('createdBy', '_id nickName').sort('dateCreated').exec(callback)
    }
};


exports.backOfficePostReplyService = function (questionId, input, callback) {
    Users.findOne({nickName: '小6客服'}, '_id', function (err, result) {
        questionService.postReplyService(result._id, questionId, input, callback)
    })
};

exports.getReportQuestionService = function (communityId, callback) {

    var data = [];

    QuestionReport.distinct("question", function (err, results) {
        async.each(results, function (questionId, callback) {
            if (communityId == '1') {
                Question.findOne({
                    _id: questionId
                }, 'desc community replies createdBy dateCreated').populate('createdBy', '_id nickName').populate('community', '_id communityName').exec(function (err, result) {
                    QuestionReport.count({question: questionId}, function (err, count) {
                        if (result != null) {
                            result._doc['count'] = count;
                            data.push(result);
                        }
                        callback();
                    })

                })
            } else {
                Question.findOne({
                    community: communityId,
                    _id: questionId
                }, 'desc community replies dateCreated').populate('community', '_id communityName').exec(function (err, result) {
                    QuestionReport.count({question: questionId}, function (err, count) {
                        if (result != null) {
                            result._doc['count'] = count;
                            data.push(result);
                        }
                        callback();
                    })
                })
            }
        }, function (err) {
            if (err) {
                var msg = {
                    "message": "get err"
                };
                callback(msg, null);
            } else {
                data.sort(function (a, b) {
                    return b.dateCreated - a.dateCreated;
                });
                callback(null, data);
            }
        })
    });
};

/**
 * 删除举报问题
 * @param questionId
 * @param callback
 */
exports.deleteReportQuestionService = function (questionId, callback) {
    async.series([
        function (callbackInner) {
            questionService.deleteQuestionService(questionId, callbackInner);
        },
        function (callbackInner) {
            QuestionReport.remove({'question': questionId}, callbackInner)
        }
    ], callback)
};

exports.getRecommendQuestionService = function (option, page, size, callback) {

    size = Number(size);
    var index = (Number(page) - 1) * size;
    var date = new Date();

    if (option['nick'] != null) {
        option['nick'] = new RegExp(option['nick']);
    }

    if (option['desc'] != null) {
        option['desc'] = new RegExp(option['desc']);
    }

    //是否有回复
    if (option['repliesflg'] == 'no') {
        option['replies'] = {$size: 0};
    } else if (option['repliesflg'] == 'yes') {
        option['replies'] = {$not: {$size: 0}};
        //option['replies'] = {$exists: true};
        //option.$where = "this.replies.length>0";
    }
    option['repliesflg'] = null;


    //opt.tag = {$exists: true};
    //opt.$where = "this.tag.length>0"
    //是否有标签
    if (option['tagflg'] == 'no') {
        option['tag'] = {$size: 0};
    } else if (option['tagflg'] == 'yes') {
        option['tag'] = {$not: {$size: 0}};
        //option['tag'] = {$exists: true};
        //option.$where = option.$where+"this.tag.length>0";
    }
    option['tagflg'] = null;

    if (option.level == 0) {
        option.level = {$ne: 1}
    }

    if (option['enddate'] == null || option['enddate'] == "") {
        option['enddate'] = '9998-12-31';
    }
    //logger.debug('enddate:' + option['enddate']);
    //logger.debug('startdate:' + option['startdate']);
    if (option['startdate'] != null && option['startdate'] != "") {
        option['dateCreated'] = {"$gte": new Date(option['startdate'])};
    }

    if (option['enddate'] != null && option['enddate'] != "") {
        if (option['dateCreated'] != null && option['dateCreated'] != "") {
            option['dateCreated'] = {
                "$gte": moment(option['startdate'])._d,
                "$lte": moment(option['enddate']).add(1, 'day')._d
            };
        } else {
            option['dateCreated'] = {"$lte": moment(option['enddate']).add(1, 'day')._d};
        }
    }
    option['startdate'] = null;
    option['enddate'] = null;

    //logger.debug(option);

    //var queryUserIn ={};option['nick'] != undefined && option['nick']!= null &&

    async.series([
        function (callback) {
            //logger.debug(option['nick']);
            var useropt = {};
            if (option['nick'] != undefined && option['nick'] != null && option['nick'] != "") {
                useropt['nickName'] = new RegExp(option['nick']);
            }
            else {
                useropt['_id'] = null;
            }
            Users.find(useropt, function (err, results) {
                if (results.length > 0) {
                    var queryUserIn = {};
                    queryUserIn["$in"] = [];
                    for (var i = 0, l = results.length; i < l; i++) {
                        queryUserIn["$in"].push(results[i]['_id']);
                    }
                    option["createdBy"] = queryUserIn;
                }
                callback(null, null);
            });
        },
        function (callback) {
            option['nick'] = null;
            //logger.debug('sdfs');
            //logger.debug(option);
            Question.count(option, function (err, count) {
                //logger.debug(option);
                //logger.debug(count);
                callback(err, Math.ceil(count / size));
            });
            //callback(null,null);
        },
        function (callback) {
            if (option.category != null) {
                //logger.debug(option);
                Question.find(option, '_id categoryOrder desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
                    .skip(index).limit(size).populate('tag', 'value').populate('replies.repliedBy', '_id nickName images authenticationStatus')
                    .populate('community', '_id communityName').populate('createdBy', '_id nickName images authenticationStatus').sort({
                        categoryOrder: -1,
                        dateLastModified: -1
                    }).exec(function (err, results) {
                        //logger.debug('results');
                        //logger.debug(results.length);
                        if (err) {
                            return callback(err);
                        } else {
                            if (results != null) {
                                results.forEach(function (question) {
                                    var data = [];
                                    if (question.tag != null) {
                                        question.tag.forEach(function (t) {
                                            data.push(t.value);
                                        });
                                        question._doc.tag = data
                                    }

                                    if (question.dateLastModified > date) {
                                        question.dateLastModified = question.dateCreated;
                                    }
                                });

                            }
                            return callback(null, results);
                        }
                    })
            } else {
                //logger.debug('ques')
                //logger.debug(option);
                Question.find(option, '_id allOrder desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
                    .skip(index).limit(size).populate('tag', 'value').populate('replies.repliedBy', '_id nickName images authenticationStatus')
                    .populate('community', '_id communityName').populate('createdBy', '_id nickName images authenticationStatus').sort({
                        allOrder: -1,
                        dateCreated: -1
                    }).exec(function (err, results) {
                        if (err) {
                            return callback(err);
                        } else {
                            if (results != null) {
                                results.forEach(function (question) {
                                    var data = [];
                                    if (question.tag != null) {
                                        question.tag.forEach(function (t) {
                                            data.push(t.value);
                                        });
                                        question._doc.tag = data
                                    }

                                    if (question.dateLastModified > date) {
                                        question.dateLastModified = question.dateCreated;
                                    }
                                })
                            }
                            return callback(null, results);
                        }
                    })
            }
        }
        //function (callback) {
        //    option['nick'] = null;
        //    logger.debug('Count');
        //    logger.debug(option);
        //    Question.count(option, function (err, count) {
        //        //logger.debug(option);
        //        logger.debug(count);
        //        callback(err, Math.ceil(count / size));
        //    });
        //},
    ], callback);
};

exports.searchUserQuestionService = function (userId, callback) {
    Question.find({
        $or: [{
            'createdBy': userId,
            'isValid': true
        }, {
            'createdBy': {'$ne': userId},
            'replies.repliedBy': userId,
            'isValid': true
        }]
    }, function (err, results) {
        var data = [];
        if (results == null) {
            callback(err, data);
        } else {
            results.forEach(function (question) {
                question._doc['isCreated'] = true;
                if (question.replies != null) {
                    if (userId != question.createdBy) {
                        question.replies.forEach(function (reply) {
                            if (userId == reply.repliedBy) {
                                question._doc['myReply'] = reply.replyDesc;
                                question._doc['isCreated'] = false;
                            }
                        });
                    }
                }
            });

            results.sort(function (a, b) {
                if (!a._doc.isCreated && b._doc.isCreated) {
                    return 1;
                }
            });
            callback(err, results)
        }
    })
};

exports.recommendQuestionService = function (questionId, flag, callback) {
    async.series([
        function (callbackInner) {
            Question.update({_id: questionId}, {recommend: flag, displayOrder: 0}, callbackInner)
        },
        function (callbackInner) {

            Question.findOne({'_id': questionId}, function (err, result) {
                var replyC = 0;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }

                Dic.findOne({'value': '推荐', 'category': '02'}, '_id', function (err, res) {
                    QuestionAndReplyCount.findOne({
                        'community': result.community,
                        'tag': res._id
                    }, '', function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.questionCount = 1;
                            temp.replyCount = replyC;
                            temp.community = result.community;
                            temp.tag = res;
                            temp.save();
                        } else {
                            if (flag == 'true') {
                                qc.questionCount += 1;
                                qc.replyCount += replyC;
                            } else {
                                qc.questionCount -= 1;
                                qc.replyCount -= replyC;
                            }
                            qc.save();
                        }
                        callbackInner(err, null);
                    });
                })
            });
        }
    ], callback)
};

exports.getFreshNewsQuestionService = function (callback) {
    freshNews.find({}, 'newsId', callback);
};

exports.addQuestionToFreshNewsService = function (input, callback) {
    async.series([
        //function (callbackInner) {
        //    freshNews.remove({tag: '话题', community: input.community._id}, callbackInner);
        //},
        function (callbackInner) {
            var temp = new freshNews();
            temp.openType = 3;
            temp.tag = freshName.question.tagName;
            temp.newsId = input._id;
            temp.createdBy = input.createdBy._id;
            temp.title = input.desc;
            temp.bgColor = freshName.question.bgColor;
            temp.community = input.community._id;
            temp.save(callbackInner);
        }
    ], callback)
};

exports.pushQuestionByTagService = function (question, callback) {
    Dic.find({value: {$in: question.tag}, category: '01'}, '_id value', function (err, tags) {
        var uList = [];
        async.each(tags, function (tag, callbackInner) {
            Users.find({hobbies: tag._id}, '_id', function (err, users) {
                if (users != null) {
                    users.forEach(function (user) {
                        if (!contains(uList, user._id)) {
                            uList.push(user._id + '');
                        }
                    })
                }
                callbackInner(null, null);
            })
        }, function (err) {
            pushRecords.find({
                messageId: question._id,
                messageType: 'question'
            }, 'toUser', function (err, users) {
                var recordUsers = [];
                if (users != null) {
                    users.forEach(function (user) {
                        recordUsers.push(user.toUser + '');
                    })
                }

                var data = [];
                console.log(recordUsers);
                console.log(uList);
                uList.forEach(function (userId) {
                    if (!contains(recordUsers, userId)) {
                        data.push(userId)
                    }
                });
                callback(null, data)

            })
        })
    })
};


function contains(array, obj) {
    var i = array.length;
    while (i--) {
        if (array[i] === obj) {
            return true;
        }
    }
    return false;
}

exports.changeQuestionCategoryService = function (questionId, category, callback) {
    var replyC = 0;
    var communityId;
    async.series([
        function (callbackInner) {
            Question.findOne({_id: questionId}, function (err, result) {
                communityId = result.community;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }
                if (result.category != null) {
                    redisClient.hincrby('q:count:' + result.community, result.category + 'QuestionCount', -1);
                    redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -replyC);
                }
                result.categoryOrder = undefined;
                result.save(callbackInner);
            });
        },
        function (callbackInner) {
            Question.update({_id: questionId}, {category: category}, callbackInner)
        },
        function (callbackInner) {
            redisClient.hincrby('q:count:' + communityId, category + 'QuestionCount', 1);
            redisClient.hincrby('q:count:' + communityId, category + 'ReplyCount', replyC);
            callbackInner(null, null);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: questionId}, {category: category}, callbackInner);
        }
    ], callback)
};

exports.changeQuestionLevelService = function (input, callback) {
    async.series([
        function (callbackInner) {
            Question.update({_id: input.questionId}, {level: input.level}, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: input.questionId}, {level: input.level}, callbackInner);
        }
    ], callback);
};

/**
 * 我的帖子1.6.0
 * @param token
 * @param ts
 * @param vcode
 * @param callback
 */
exports.myReleasedQuestionsService = function (token, ts, vcode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED, null)
        } else {
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var opt = {
                isValid: true,
                createdBy: user._id,
                //community: user.community._id,
                dateCreated: {$lt: date}
            };
            if (vcode >= 200000) {
                opt.category = {$ne: 'secondhand'}
            }

            Question.find(opt, '_id desc browserCount category tag images replies dateCreated community praiseCount createdBy score status topicId')
                .limit(listPageSize).sort({dateCreated: -1})
                .populate('community', 'communityName')
                .populate('createdBy', '_id nickName')
                .populate('tag', 'value')
                .exec(function (err, result) {
                    if (result != null) {
                        async.eachSeries(result, function (question, callbackInner) {
                            //回复数量
                            question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                            //浏览量
                            question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                            question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);
                            question._doc.replies = undefined;
                            question._doc.browserCount = undefined;
                            /*  宝宝树66小区二次改造    add   luolh  20170816   start   */
                            //question._doc.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';
                            question._doc.shareUrl = 'http://' + questionShareHost + QUESTION_SHARE_URL + '?v=1.0';
                            /*  宝宝树66小区二次改造    add   luolh  20170816   end   */
                            if (question.topicId != null)
                                question._doc.topicUrl = h5Host + '/app/topic/index.html?tid=' + question.topicId;

                            questionPraise.findOne({question: question._id, user: user._id}, function (err, result) {
                                if (result == null) {
                                    question._doc['isPraise'] = false;
                                } else {
                                    question._doc['isPraise'] = true;
                                }
                                callbackInner();
                            })
                        }, function () {
                            callback(null, result)
                        })
                    } else {
                        callback(err, result)
                    }
                })
        }
    })
};

/**
 * 我的回复1.6.0
 * @param token
 * @param ts
 * @param callback
 */
exports.myReplyQuestionsService = function (token, ts, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED, null)
        } else {
            var index = Number(ts) * listPageSize;
            var data = [];

            ugcReply.find({
                $or: [{community: user.community._id}, {aroundCommunity: user.community._id}],
                repliedBy: user._id
            }).skip(index).limit(listPageSize)
                .sort('-dateCreated')
                .exec(function (err, result) {
                    if (result != null) {
                        async.eachSeries(result, function (ugc, callbackInner) {
                            if (ugc.category == 'neighbourActivity') {
                                neighbourActivity.findOne({_id: ugc.ugcId}, '_id title  replies._id replies.images replies.replyDesc replies.dateReplied replies.repliedBy desc category dateCreated createdBy images')
                                    .populate('tag', 'category value _id')
                                    .populate('createdBy', '_id nickName images userType authenticationStatus')
                                    .exec(function (err, activity) {
                                        if (activity != null) {

                                            if (activity.replies != null) {
                                                activity.replies.forEach(function (reply) {
                                                    if (reply._id + '' == ugc.replyId) {
                                                        activity._doc['myReply'] = reply;
                                                    }
                                                });
                                            }
                                            activity._doc.replies = undefined;

                                            if (activity._doc.myReply != null && activity._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                replyAt.findOne({replyId: activity._doc.myReply._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            activity._doc.myReply.replyDesc = activity._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    data.push(activity);
                                                    callbackInner()
                                                }).populate('uList', '_id nickName');
                                            } else {
                                                data.push(activity);
                                                callbackInner(err);
                                            }
                                        } else {
                                            callbackInner(err);
                                        }
                                    })
                            } else {
                                Question.findOne({
                                    _id: ugc.ugcId,
                                    'isValid': true
                                }, '_id desc replies._id replies.replyDesc replies.images replies.repliedBy replies.dateReplied category dateCreated createdBy images')
                                    .populate('createdBy', '_id nickName images userType authenticationStatus').exec(function (err, question) {
                                        if (question != null) {
                                            if (question.replies != null) {
                                                question.replies.forEach(function (reply) {
                                                    if (reply._id + '' == ugc.replyId) {
                                                        question._doc['myReply'] = reply;
                                                    }
                                                });
                                            }
                                            question._doc.replies = undefined;

                                            if (question._doc.myReply != null && question._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                replyAt.findOne({replyId: question._doc.myReply._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            question._doc.myReply.replyDesc = question._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    data.push(question);
                                                    callbackInner()
                                                }).populate('uList', '_id nickName');
                                            } else {
                                                data.push(question);
                                                callbackInner(err);
                                            }
                                        } else {
                                            callbackInner();
                                        }
                                    })
                            }
                        }, function (err) {
                            callback(err, data);
                        })
                    } else {
                        callback(null, []);
                    }
                });
        }
    })
};

/**
 * 我的收藏1.6.0
 * @param token
 * @param ts
 * @param vcode
 * @param callback
 */
exports.myFollowupQuestionsService = function (token, ts, vcode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED, null)
        } else {
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var data = [];

            UserFollowups.find({
                category: 'question',
                user: user._id,
                question: {$ne: null},
                dateCreated: {$lt: date}
            }, 'question dateCreated').sort('-dateCreated')
                .limit(listPageSize).exec(function (err, result) {
                    if (result != null && result.length > 0) {
                        async.eachSeries(result, function (fl, callbackInner) {
                            if (fl.question != null) {
                                Question.findOne({_id: fl.question}, '_id desc browserCount category tag images replies dateCreated community createdBy praiseCount')
                                    .populate('community', 'communityName')
                                    .populate('createdBy', 'nickName images userType authenticationStatus')
                                    .populate('tag', 'value')
                                    .exec(function (err, question) {
                                        if (question != null) {
                                            if (vcode >= 200000 && question.category == 'secondhand') {
                                                callbackInner()
                                            } else {
                                                //回复数量
                                                question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                                                //浏览量
                                                question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                                                question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);
                                                question._doc.replies = undefined;
                                                question._doc.browserCount = undefined;

                                                question._doc['followTime'] = fl.dateCreated;
                                                question._doc.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';

                                                questionPraise.findOne({
                                                    question: question._id,
                                                    user: user._id
                                                }, function (err, result) {
                                                    if (result == null) {
                                                        question._doc['isPraise'] = false;
                                                    } else {
                                                        question._doc['isPraise'] = true;
                                                    }
                                                    data.push(question);
                                                    callbackInner();

                                                });
                                            }
                                        } else {
                                            callbackInner()
                                        }
                                    })
                            }
                        }, function (err) {
                            callback(null, data)
                        })
                    } else {
                        callback(null, data);
                    }
                })
        }
    })
};

/**
 * 问题点赞1.6.0
 * @param token
 * @param questionId
 * @param callback
 */
exports.praiseQuestionService = function (token, questionId, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            async.series([
                function (callbackInner) {
                    questionPraise.findOne({user: token, question: questionId}, function (err, result) {
                        if (!err && result == null) {
                            var temp = new questionPraise();
                            temp.question = questionId;
                            temp.user = token;
                            temp.community = user.community._id;
                            temp.save();
                            Question.update({_id: questionId}, {$inc: {praiseCount: 1}}, callbackInner);
                        } else {
                            if (err) logger.error(err.message);
                            callbackInner({status: 0, message: '已经赞过了'});
                        }
                    })
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, 'praiseCount community category createdBy', function (err, result) {
                        var praiseCount = toolUtil.transformNumber(result.praiseCount);

                        var key = 'catch:q:all:' + result.community;
                        var categoryKey = 'catch:q:category:' + result.category + ':' + result.community;
                        redisClient.del(key);
                        redisClient.del(categoryKey);

                        callbackInner(null, {
                            count: praiseCount,
                            createdBy: result.createdBy,
                            community: result.community
                        });
                    })
                },
                function (callbackInner) {
                    taskService.finishTaskService(user._id, 'praise', callbackInner)
                }
            ], callback)
        }
    });
};

/**
 * 取消问题点赞
 * @param token
 * @param questionId
 * @param callback
 */
exports.cancelPraiseQuestionService = function (token, questionId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED);
        } else {
            async.series([
                function (callbackInner) {

                    questionPraise.findOne({user: user._id, question: questionId}, function (err, result) {
                        if (err || result == null) {
                            if (err) logger.error(err.message);
                            callbackInner({status: 0, message: '未点赞，无法取消'});
                        } else {
                            questionPraise.remove({user: user._id, question: questionId}, callbackInner)
                        }
                    });
                },
                function (callbackInner) {
                    Question.update({_id: questionId}, {$inc: {praiseCount: -1}}, callbackInner);
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, 'praiseCount community category createdBy', function (err, result) {
                        var praiseCount = toolUtil.transformNumber(result.praiseCount);

                        var key = 'catch:q:all:' + result.community;
                        var categoryKey = 'catch:q:category:' + result.category + ':' + result.community;
                        redisClient.del(key);
                        redisClient.del(categoryKey);

                        var data = {
                            count: praiseCount,
                            createdBy: result.createdBy
                        };

                        callbackInner(null, data);
                    })
                }
            ], callback)
        }
    })
};

exports.praiseUsersService = function (ugcId, ts, category, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var opt = {
                dateCreated: {$lt: date}
            };

            if (category == 'neighbourActivity') {
                opt.activity = ugcId;
            } else {
                opt.question = ugcId;
            }

            questionPraise.find(opt).sort('-dateCreated').limit(listPageSize)
                .populate('user', 'nickName images userType gender authenticationStatus roomUnit showUnit userRole')
                .populate('community', 'communityName')
                .exec(function (err, result) {
                    var data = [];
                    if (result != null) {
                        result.forEach(function (temp) {
                            if (temp.user != null) {

                                if (temp.community != null) {
                                    var isOtherCommunity = user.community._id != temp.community._id + '';
                                }

                                temp.user._doc.roomUnit = !isNaN(temp.user.roomUnit) ? temp.user.roomUnit + '单元' : temp.user.roomUnit;

                                if ((temp.user.showUnit != null && !temp.user.showUnit) || isOtherCommunity) {
                                    temp.user.roomUnit = undefined;
                                }
                                temp.user.showUnit = undefined;

                                var a = {
                                    praiseTime: temp.dateCreated,
                                    user: temp.user,
                                    community: temp.community
                                };
                                data.push(a);
                            }
                        })
                    }
                    callback(null, data);
                })
        }
    })
};

/**
 * 其他用户的帖子1.6.0
 * @param userId
 * @param token
 * @param ts
 * @param callback
 */
exports.otherReleasedQuestionsService = function (userId, token, ts, communityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED, null)
        } else {
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            Users.findById(userId, function (err, other) {
                if (other == null) {
                    callback(null, [])
                } else {
                    var opt = {
                        isValid: true,
                        createdBy: userId,
                        community: communityId ? communityId : other.community,
                        dateCreated: {$lt: date}
                    };
                    //if (other.community + '' == user.community._id) {
                    //    opt.community = user.community._id
                    //} else {
                    //    opt.aroundCommunity = user.community._id;
                    //}
                    Question.find(opt, '_id desc browserCount fromFlag category tag images replies dateCreated community praiseCount createdBy score status topicId')
                        .limit(listPageSize).sort({dateCreated: -1})
                        .populate('community', 'communityName location')
                        .populate('createdBy', '_id nickName')
                        .populate('tag', 'value')
                        .exec(function (err, result) {
                            if (result != null) {
                                async.eachSeries(result, function (question, callbackInner) {

                                    var distance = geolib.getDistance(
                                        {
                                            latitude: user.community.location.latitude,
                                            longitude: user.community.location.longitude
                                        },
                                        {
                                            latitude: question.community.location.latitude,
                                            longitude: question.community.location.longitude
                                        }
                                    );

                                    if (distance > 0 && question.fromFlag != 'operate')
                                        question._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';

                                    //回复数量
                                    question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                                    //浏览量
                                    question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                                    question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);
                                    question._doc.replies = undefined;
                                    question._doc.browserCount = undefined;
                                    question._doc.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';
                                    if (question.topicId != null)
                                        question._doc.topicUrl = h5Host + '/app/topic/index.html?tid=' + question.topicId;
                                    questionPraise.findOne({
                                        question: question._id,
                                        user: user._id
                                    }, function (err, result) {
                                        question._doc['isPraise'] = result != null;
                                        callbackInner();
                                    })
                                }, function () {
                                    callback(null, result)
                                })
                            } else {
                                callback(err, result)
                            }
                        })
                }
            });
        }
    })
};


/**
 * 其他用户的回复1.6.0
 * @param userId
 * @param token
 * @param ts
 * @param callback
 */
exports.otherReplyQuestionsService = function (userId, token, ts, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED, null)
        } else {
            var index = Number(ts) * listPageSize;
            var data = [];

            Users.findById(userId, function (err, other) {
                if (other == null) {
                    callback(null, [])
                } else {
                    var opt = {
                        repliedBy: userId
                    };
                    if (other.community + '' == user.community._id) {
                        opt['$or'] = [{aroundCommunity: user.community._id}, {
                            community: user.community._id
                        }];
                    } else {
                        opt['$or'] = [{aroundCommunity: user.community._id}, {
                            community: user.community._id,
                            aroundCommunity: other.community
                        }]
                    }

                    ugcReply.find(opt).skip(index).limit(listPageSize)
                        .sort('-lastReply')
                        .exec(function (err, result) {
                            if (result != null) {
                                async.eachSeries(result, function (ugc, callbackInner) {
                                    if (ugc.category == 'neighbourActivity') {
                                        neighbourActivity.findOne({_id: ugc.ugcId}, '_id title  replies._id replies.images replies.replyDesc replies.dateReplied replies.repliedBy desc category dateCreated createdBy images')
                                            .populate('tag', 'category value _id')
                                            .populate('createdBy', '_id nickName images userType authenticationStatus')
                                            .exec(function (err, activity) {
                                                if (activity != null) {

                                                    if (activity.replies != null) {
                                                        activity.replies.forEach(function (reply) {
                                                            if (ugc.replyId == reply._id + '') {
                                                                activity._doc['myReply'] = reply;
                                                            }
                                                        });
                                                    }
                                                    activity._doc.replies = undefined;

                                                    if (activity._doc.myReply != null && activity._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                        replyAt.findOne({replyId: activity._doc.myReply._id + ''}, function (err, at) {
                                                            if (at != null && at.uList != null) {
                                                                at.uList.forEach(function (temp, i) {
                                                                    activity._doc.myReply.replyDesc = activity._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                                });
                                                            }
                                                            data.push(activity);
                                                            callbackInner()
                                                        }).populate('uList', '_id nickName');
                                                    } else {
                                                        data.push(activity);
                                                        callbackInner(err);
                                                    }
                                                } else {
                                                    callbackInner(err);
                                                }
                                            })
                                    } else {
                                        Question.findOne({
                                            _id: ugc.ugcId,
                                            'isValid': true
                                        }, '_id desc replies._id replies.replyDesc replies.images replies.repliedBy replies.dateReplied category dateCreated createdBy images')
                                            .populate('createdBy', '_id nickName images userType authenticationStatus').exec(function (err, question) {
                                                if (question != null) {
                                                    if (question.replies != null) {
                                                        question.replies.forEach(function (reply) {
                                                            if (ugc.replyId == reply._id + '') {
                                                                question._doc['myReply'] = reply;
                                                            }
                                                        });
                                                    }
                                                    question._doc.replies = undefined;

                                                    if (question._doc.myReply != null && question._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                        replyAt.findOne({replyId: question._doc.myReply._id + ''}, function (err, at) {
                                                            if (at != null && at.uList != null) {
                                                                at.uList.forEach(function (temp, i) {
                                                                    question._doc.myReply.replyDesc = question._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                                });
                                                            }
                                                            data.push(question);
                                                            callbackInner()
                                                        }).populate('uList', '_id nickName');
                                                    } else {
                                                        data.push(question);
                                                        callbackInner(err);
                                                    }
                                                } else {
                                                    callbackInner();
                                                }
                                            })
                                    }
                                }, function (err) {
                                    callback(err, data);
                                })
                            } else {
                                callback(null, []);
                            }
                        });
                }
            });
        }
    })
};

//exports.getTestAround = function (communityId, aroundCommunity, callback) {
//    Community.findOne({_id: communityId}, 'groups', function (err, community) {
//        if (community.groups.indexOf('55c2ce4d5cd6d99e5cb10508') == -1) {
//            callback(null, aroundCommunity);
//        } else {
//            Community.find({groups: '55c2ce4d5cd6d99e5cb10508', _id: {$ne: communityId}}, function (err, result) {
//                var data = [];
//                result.forEach(function (temp) {
//                    data.push(temp._id);
//                });
//                callback(null, data);
//            })
//        }
//    });
//};


/**
 * 1.7.0 新增问题
 * @param token
 * @param input
 * @param callback
 */
exports.addNewQuestionService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {

            if (user.community._id == '564310b186acfe4f5fa87b4d') {
                input.around = false;
            }

            exports.getAroundCommunityList(user, function (value) {
                if (input.around == true && input.parentCommunity == null) {
                    input.aroundCommunity = value
                }
                var question;
                async.series([
                    function (callbackInner) {

                        var desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

                        var temp = new Question();
                        temp.category = input.category;
                        temp.desc = desc;
						/*/!*  宝宝树66小区二次改造    add   gct  20170825   start   *!/
                        temp.topFlg=input.topFlg,
                        /!*  宝宝树66小区二次改造    add   gct  20170825   end   *!/*/
                        temp.images = input.images;
                        temp.status = '未解决';
                        temp.createdBy = user._id;
                        temp.score = input.score;
                        /*  宝宝树66小区二次改造    add   guo  20170825   start   */
                        temp.topFlg=input.topFlg;
                        /*  宝宝树66小区二次改造    add   guo  20170825   end   */
                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
                        // redis保存取得用户选择小区ID,城市ID
                        var currUserId = user._id; // 用户ID
                        var currCommunityId = ''; // 小区ID
                        var currCityId = ''; // 城市ID

                        async.parallel([
                            function(callbackInner) {
                                redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
                                    if (!errComm) currCommunityId = replyComm;
                                    callbackInner(null, replyComm);
                                });
                            },
                            function(callbackInner) {
                                redisClient.get(currUserId + ":currCityId", function (errCity, replyCity) {
                                    if (!errCity) currCityId = replyCity;
                                    callbackInner(null, replyCity);
                                });
                            }], function(err, result) {
                                currCommunityId = result[0];
                                currCityId = result[1];
                                if(currCommunityId == null || currCommunityId == '') {
                                    currCommunityId = user.community._id;
                                }
                                if(currCityId == null || currCityId == '') {
                                    currCityId = user.community.cityId;
                                }
                                temp.community = input.parentCommunity == null ? currCommunityId: input.parentCommunity; // 新
                                temp.city = input.parentCity == null ? currCityId : input.parentCity;// 新
                                // temp.community = input.parentCommunity == null ? user.community._id : input.parentCommunity; // 旧
                                // temp.city = input.parentCity == null ? user.community.cityId : input.parentCity; // 旧

                                temp.key = input.key;
                                temp.aroundCommunity = input.aroundCommunity;
                                temp.tag = input.tag;
                                temp.fromFlag = input.fromFlag;
                                temp.topicId = input.topicId;

                                // 紧急通知置顶一天
                                if (input.category == 'alert') {
                                    temp.topBeginDate = new Date();
                                    temp.topEndDate = new Date(temp.topBeginDate.getTime()+60*60*24*1000);
                                }

                                if (user.community.communityType == 0) {
                                    temp.fromFlag = 'operate'
                                }

                                //打标签
                                //  宝宝树66小区二次改造   recommond失效 mod  luolh  20170724   start
                                // restClient.get('http://' + RecommendHost + ':8002?data=' + input.desc, function (data, response) {
                                //     if (response.statusCode == 200 && data != null && data != 'unknown' && data != '') {
                                //         try {
                                //             var sensitive = JSON.parse(data).sensitive;
                                //
                                //             if (sensitive != null) {
                                //                 temp.desc = sensitive;
                                //             }
                                //             temp.save(function (err, result) {
                                //                 question = result;
                                //                 callbackInner(err, result)
                                //             });
                                //         } catch (e) {
                                //             logger.error("json parse data error--" + data);
                                //             temp.save(function (err, result) {
                                //                 question = result;
                                //                 callbackInner(err, result)
                                //             })
                                //         }
                                //     } else {
                                //         temp.save(function (err, result) {
                                //             question = result;
                                //             callbackInner(err, result)
                                //         })
                                //     }
                                // }).on('error', function (err) {
                                //     logger.error('recommend server err --' + err.message);
                                //     temp.save(function (err, result) {
                                //         question = result;
                                //         callbackInner(err, result)
                                //     });
                                // });
                                temp.save(function (err, result) {
                                    question = result;
                                    callbackInner(err, result)
                                });
                                //  宝宝树66小区二次改造   recommond失效 mod  luolh  20170724   start
                        });
                        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   end   */
                    },
                    function (callbackInner) {
                        var temp = new ugcIndex();
                        temp.ugcId = question._id;
                        temp.category = input.category;
                        temp.community = question.community;
                        temp.createdBy = question.createdBy;
                        temp.aroundCommunity = question.aroundCommunity;
                        if (question.tag != null)
                            temp.tag = question.tag;
                        temp.save(function (err, result) {
                            callbackInner(null, user.community.communityName)
                        });
                    },
                    function (callbackInner) {
                        /*  宝宝树66小区二次改造    mod   chenf  20170723   start   */
                        /*if (input.category == 'question')*/
                        if (input.category == 'share')
                        /*   宝宝树66小区二次改造    mod   chenf  20170723   end   */
                            taskService.finishTaskService(user._id, 'release', callbackInner);
                        else
                            callbackInner();
                    },
                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   start   */
                    function (callbackInner) {
                        userService.pushMessageToFollowers(user._id, input.category, callbackInner);
                    }
                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   end   */
                ], callback);
            });
        }
    })
};

/**
 * 发帖、二手 需要的周边数据
 * @param user
 * @param callback
 */
exports.getAroundCommunityList = function (user, callback) {
    if (user.community.communityType == 1) return callback([]);

    Community.find({
        isValid: true,
        cityId: user.community.cityId,
        _id: {$ne: user.community._id},
        location: {
            $nearSphere: [user.community.location.longitude, user.community.location.latitude],
            $maxDistance: 3 / 6371
        }
    }, '_id').limit(100).exec(function (err, result) {
        if (result == null) return callback([]);
        var list = [];
        result.forEach(function (item) {
            list.push(item._id)
        });
        callback(list)
    })
};

/**
 * 1.7.0新增问题回复
 * @param token
 * @param questionId
 * @param input
 * @param callback
 */
exports.addNewReplyService = function (token, questionId, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED);
        } else {
            var question, replyC;
            var replyId;
            async.series([
                function (callbackInner) {

                    // if (input.replyDesc == null || input.replyDesc == '') {
                    //     callbackInner({message: '回复内容不能为空'}, null);
                    // } else {
                        Question.findOne({_id: questionId}, function (err, result) {
                            if (result == null) {
                                var msg = {
                                    status: 0,
                                    message: '问题不存在或已被删除'
                                };
                                callbackInner(msg, null);
                            } else {
                                question = result;
                                question._doc['huanxinName'] = user.huanxinUserName;
                                callbackInner(err, question);
                            }
                        });
                    // }
                },
                function (callbackInner) {
                    exports.getUserReplyCommunity(user, question.community, function (replyCommunity) {
                        var desc = input.replyDesc.replace(/[\r\n]{2,}/g, "\n").trim();
                        var rep = {
                            'replyDesc': desc,
                            'replyTo': input.replyTo,
                            'quoteId': input.quoteId,
                            'repliedBy': user._id,
                            'community': replyCommunity,
                            'images': input.images
                        };
                        Question.update({_id: questionId}, {
                            $push: {'replies': rep},
                            dateLastModified: new Date()
                        }).exec();

                        replyC = replyCommunity;
                        ugcIndex.update({ugcId: questionId}, {lastReply: new Date()}, function (err, result) {
                            callbackInner(null, replyCommunity);
                        });
                    });
                },
                function (callbackInner) {
                    if (question.category != null)
                        redisClient.hincrby('q:count:' + question.community, question.category + 'ReplyCount', 1);
                    callbackInner();
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        callbackInner(err, result);

                        var temp = new ugcReply();
                        temp.ugcId = result._id;
                        temp.replyId = result.replies[result.replies.length - 1]._id;
                        temp.category = result.category;
                        temp.community = result.community;
                        temp.createdBy = result.createdBy;
                        temp.aroundCommunity = result.aroundCommunity;
                        temp.repliedBy = user._id;
                        temp.save();

                        var index = new replyIndex();
                        index.contentId = result._id;
                        index.replyId = result.replies[result.replies.length - 1]._id;
                        index.repliedBy = user._id;
                        index.community = replyC;
                        index.save();
                    }).populate('replies.repliedBy', '_id nickName images userType authenticationStatus roomUnit').populate('replies.replyTo', '_id nickName images').populate('replies.community', 'communityName')
                },
                /*  宝宝树66小区二次改造    del   chenf  20170719   start   */
                /*function (callbackInner) {
                    if (question.category == 'question')
                        taskService.finishTaskService(user._id, 'reply', callbackInner);
                    else
                        callbackInner();
                }*/
                /*  宝宝树66小区二次改造    del   chenf  20170719   start   */
            ], callback)
        }
    })
};

exports.getUserReplyCommunity = function (user, questionCommunity, callback) {
    if (user.community._id == questionCommunity + '') return callback(user.community._id);

    userCommunity.find({user: user._id}, 'community').populate('community', 'location cityId')
        .exec(function (err, result) {
            if (result == null || result.length < 2) return callback(user.community._id);
            Community.findOne({_id: questionCommunity}, 'location cityId', function (err, qComm) {
                var list = [];
                result.forEach(function (item) {
                    if (item.community.cityId + '' == qComm.cityId + '') list.push(item);
                });
                if (list.length == 0) return callback(user.community._id);
                if (list.length == 1) return callback(list[0].community._id);

                list.forEach(function (c) {
                    c._doc.dis = geolib.getDistance(
                        {latitude: c.community.location.latitude, longitude: c.community.location.longitude},
                        {
                            latitude: qComm.location.latitude,
                            longitude: qComm.location.longitude
                        }
                    );
                });

                list.sort(function (a, b) {
                    return a._doc.dis - b._doc.dis;
                });
                return callback(list[0].community._id)
            })
        })
};

exports.replaceUgcDescAtService = function (desc, uList, callback) {
    if (desc.indexOf(atFlag) != -1 && uList != null && uList.length > 0) {

        var opt = [];
        uList.forEach(function (id) {
            opt.push({_id: id});
        });

        Users.find({$or: opt}, 'nickName', function (err, result) {
            result.forEach(function (temp, i) {
                desc = desc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
            });
            callback(null, desc);
        });
    } else {
        callback(null, desc)
    }
};

exports.getTopic = function (input, callback) {
    toolUtil.getUserByToken(input.token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED);
        } else {
            topic.findOne({_id: input.topicId}, function (err, result) {
                topic.update({_id: input.topicId}, {$inc: {browserCount: 1}}).exec();
                if (result.images != null) {
                    result._doc.topicImage = imgHost + result.images[0].imageURL + '?imageView2/1/w/200/h/200/q/85/format/jpg';
                    result._doc.bigImg = result.images[0].imageURL;
                }
                callback(err, result);
            });
        }
    });
};

exports.getShareByTopicId = function (input, callback) {
    toolUtil.getUserByToken(input.token, function (err, user) {
            if (err) {
                callback(ErrorMessage.LOGON_EXPIRED);
            } else {
                var opt = {
                    isValid: true
                };

                if (input.ts == 0) {
                    //opt.dateCreated = {$gt: Number(input.ts)};
                } else {
                    opt.dateCreated = {$lt: Number(input.ts)};
                }

                opt.topicId = input.topicId;
                //opt.community = user.community._id;
                if (input.around == 'around') {
                    opt['$and'] = [{$or: [{community: user.community._id}, {aroundCommunity: user.community._id}, {fromFlag: 'operate'}]},
                        {$or: [{category: 'share'}, {category: 'advertisement'}]}];
                } else {
                    opt['$and'] = [{
                        $or: [{community: user.community._id},
                            {
                                city: user.community.cityId,
                                'aroundCommunity.0': {$exists: true}
                            }, {fromFlag: 'operate'}]
                    }, {$or: [{category: 'share'}, {category: 'advertisement'}]}];
                    //opt['$or'] = [{category: 'share'}, {category: 'advertisement'}];
                }

                Question.find(opt, 'praiseCount _id desc categoryOrder community replies score ' +
                    'category status images replies dateCreated createdBy')
                    //.populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                    .populate('community', '_id communityName')
                    .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
                    .sort({dateCreated: -1}).limit(listPageSize).exec(function (err, results) {
                        if (err) {
                            callback(err, null)
                        } else {
                            async.each(results, function (temp, callbackInner) {

                                    if (temp.createdBy.images != null && temp.createdBy.images.length > 0) {
                                        if (temp.createdBy.images[0].imageURL.indexOf("http://") < 0) {
                                            temp._doc.headImg = imgHost + temp.createdBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                        } else {
                                            temp._doc.headImg = temp.createdBy.images[0].imageURL;
                                        }
                                    }
                                    if (temp.images != null) {
                                        for (var i = 0; i < temp.images.length; i++) {
                                            var tempImg = temp.images[i];
                                            tempImg._doc.bigImg = tempImg.imageURL;
                                            if (tempImg.imageURL.indexOf("http://") < 0) {
                                                tempImg.imageURL = imgHost + tempImg.imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                            }
                                        }
                                    }
                                    temp._doc.dateCreated = temp.dateCreated.getTime();
                                    questionPraise.findOne({
                                        question: temp._id,
                                        user: user._id
                                    }, function (err, result) {
                                        temp._doc.isPraise = result != null ? true : false;
                                        callbackInner();
                                    });
                                }
                                ,
                                function (err) {
                                    var data = {};

                                    //新帖子数量超过一页返回下一页时间戳
                                    if (results.length >= listPageSize) {
                                        data.nextTs = results[results.length - 1].dateCreated;
                                    }

                                    data.list = results;

                                    callback(err, data);
                                }
                            )
                            ;
                        }
                    }
                )
                ;
            }
        }
    )
    ;
};
/*  宝宝树66小区二次改造    add   chenf  20170802   start   */
exports.findCreateBy = function (questionId,callback) {
    Question.find({_id:questionId},"createdBy",function (err,result) {
        callback(err,result);
    })
};
/*  宝宝树66小区二次改造    add   chenf  20170802   start   */
